在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given two integers We define an inverse pair as following: For Since the answer may be very large, the answer should be modulo 109 + 7. Example 1: Input: n = 3, k = 0 Output: 1 Explanation: Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pair. Example 2: Input: n = 3, k = 1 Output: 2 Explanation: The array [1,3,2] and [2,1,3] have exactly 1 inverse pair. Note:
给出两个整数 逆序对的定义如下:对于数组的第 由于答案可能很大,只需要返回 答案 mod 109 + 7 的值。 示例 1: 输入: n = 3, k = 0 输出: 1 解释: 只有数组 [1,2,3] 包含了从1到3的整数并且正好拥有 0 个逆序对。 示例 2: 输入: n = 3, k = 1 输出: 2 解释: 数组 [1,3,2] 和 [2,1,3] 都有 1 个逆序对。 说明:
Runtime: 280 ms
Memory Usage: 25.2 MB
1 class Solution { 2 func kInversePairs(_ n: Int, _ k: Int) -> Int { 3 var M:Int = 1000000007 4 var dp:[[Int]] = [[Int]](repeating:[Int](repeating:0,count:k + 1),count:n + 1) 5 dp[0][0] = 1 6 if n >= 1 7 { 8 for i in 1...n 9 { 10 dp[i][0] = 1 11 if k >= 1 12 { 13 for j in 1...k 14 { 15 dp[i][j] = (dp[i - 1][j] + dp[i][j - 1]) % M 16 if j >= i 17 { 18 dp[i][j] = (dp[i][j] - dp[i - 1][j - i] + M) % M 19 } 20 } 21 } 22 } 23 } 24 return dp[n][k] 25 } 26 }
|
请发表评论