在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ We are given A valid permutation is a permutation
How many valid permutations are there? Since the answer may be large, return your answer modulo Example 1: Input: 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:
我们给出
有多少个有效排列?因为答案可能很大,所以请返回你的答案模 示例: 输入:"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) 提示:
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 }
|
请发表评论