[Swift]LeetCode629. K个逆序对数组 | K Inverse Pairs Array

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-tcpgquyp-me.html 
➤若是连接不是山青咏芝的博客园地址,则多是爬取做者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持做者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Given two integers n and k, find how many different arrays consist of numbers from 1 to n such that there are exactly k inverse pairs.git

We define an inverse pair as following: For ith and jthelement in the array, if i < j and a[i] > a[j] then it's an inverse pair; Otherwise, it's not.github

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

Input: n = 3, k = 1
Output: 2
Explanation: 
The array [1,3,2] and [2,1,3] have exactly 1 inverse pair. 

Note:code

  1. The integer n is in the range [1, 1000] and k is in the range [0, 1000].

给出两个整数 n 和 k,找出全部包含从 1 到 n 的数字,且刚好拥有 k 个逆序对的不一样的数组的个数。htm

逆序对的定义以下:对于数组的第i个和第 j个元素,若是满i < j且 a[i] > a[j],则其为一个逆序对;不然不是。blog

因为答案可能很大,只须要返回 答案 mod 109 + 7 的值。element

示例 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 个逆序对。

说明:

  1.  n 的范围是 [1, 1000] 而且 k 的范围是 [0, 1000]。

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 }
相关文章
相关标签/搜索