1. 程式人生 > >[Swift]LeetCode903. DI 序列的有效排列 | Valid Permutations for DI Sequence

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

The pan clas stand ring note ans lse run

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

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

  • 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:

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:

  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],使得對所有的 i

  • 如果 S[i] == ‘D‘,那麽 P[i] > P[i+1],以及;
  • 如果 S[i] == ‘I‘,那麽 P[i] < P[i+1]

有多少個有效排列?因為答案可能很大,所以請返回你的答案模 10^9 + 7

.

示例:

輸入:"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) 

提示:

  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 }

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