[Swift]LeetCode903. DI 序列的有效排列 | Valid Permutations for DI Sequence

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-hvojtfiw-me.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".)git

valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i:github

  • If S[i] == 'D', then P[i] > P[i+1], and;
  • If S[i] == 'I', then P[i] < P[i+1].

How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7微信

Example 1:spa

Input: "DID"
Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0) 

Note:code

  1. 1 <= S.length <= 200
  2. S consists only of characters from the set {'D', 'I'}.

咱們給出 S,一個源於 {'D', 'I'} 的長度爲 n 的字符串 。(這些字母表明 「減小」 和 「增長」。)
有效排列 是對整數 {0, 1, ..., n} 的一個排列 P[0], P[1], ..., P[n],使得對全部的 ihtm

  • 若是 S[i] == 'D',那麼 P[i] > P[i+1],以及;
  • 若是 S[i] == 'I',那麼 P[i] < P[i+1]

有多少個有效排列?由於答案可能很大,因此請返回你的答案模 10^9 + 7blog

示例:字符串

輸入:"DID"
輸出:5
解釋:
(0, 1, 2, 3) 的五個有效排列是:
(1, 0, 3, 2)
(2, 0, 3, 1)
(2, 1, 3, 0)
(3, 0, 2, 1)
(3, 1, 2, 0) 

提示:get

  1. 1 <= S.length <= 200
  2. S 僅由集合 {'D', 'I'} 中的字符組成。

Runtime: 16 ms
Memory Usage: 19.8 MB
 1 class Solution {
 2     func numPermsDISequence(_ S: String) -> Int {
 3         var n:Int = S.count
 4         var mod:Int = Int(1e9 + 7)
 5         var dp:[[Int]] = [[Int]](repeating:[Int](repeating:0,count:n + 1),count:n + 1)
 6         for j in 0...n
 7         {
 8             dp[0][j] = 1
 9         }
10         let arrS:[Character] = Array(S)
11         for i in 0..<n
12         {
13             if arrS[i] == "I"
14             {
15                 var j:Int = 0
16                 var cur:Int = 0
17                 while(j < n - i)
18                 {                     
19                     cur = (cur + dp[i][j]) % mod
20                     dp[i + 1][j] = cur
21                     j += 1
22                 }
23             }
24             else
25             {
26                 var j:Int = n - i - 1
27                 var cur:Int = 0
28                 while(j >= 0)
29                 {
30                     cur = (cur + dp[i][j + 1]) % mod
31                     dp[i + 1][j] = cur
32                     j -= 1
33                 }
34             }
35         }
36         return dp[n][0]
37     }
38 }
相關文章
相關標籤/搜索