629. K Inverse Pairs Array
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.
We define an inverse pair as following: For ith and jth element in the array, if i < j and a[i] > a[j] then it’s an inverse pair; Otherwise, it’s not.
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:
The integer n is in the range [1, 1000] and k is in the range [0, 1000].
题目大意:
给定n和k,找出大小为n且拥有k个逆序对的数组个数
思路:
这是一道典型的动态规划题目,我们来尝试推出公式
我们用dp[i][k]来表示用前i个数且拥有k个逆序对的时候的
dp[i][k] = dp[i-1][k]+ dp[i-1][k-1]+ dp[i-1][k-2]..... dp[i-1][k-i+1] 【1】
假设我们已经排好了i-1个数,这是得到第i个数,我们可以得知这个第i个数大于当前数组的所有数,因此当第i个数从当前位置向前移动时总会增加新的逆序对,且增加的逆序对从0到i-1不等,取决于插入的位置。
同样的我们有
dp[i][k-1] = dp[i-1][k-1]+ dp[i-1][k-1]+ dp[i-1][k-2]..... dp[i-1][k-i] 【2】
结合公式【1】我们可以得到
dp[i][k] = dp[i-1][k]+dp[i][k-1]-dp[i-1][k-i] 【3】
公式3中需要注意的是,第三项dp[i-1][k-i] 不总是存在,当i>k时这项不应存在
代码如下所示:
class Solution {
const int mod = pow(10, 9) + 7;
public:
int kInversePairs(int n, int k) {
vector<vector<int>> dp(n+1, vector<int>(k+1));
dp[0][0] = 1;
for(int i=1;i<=n;i++){
dp[i][0] = 1;
for(int j = 1; j <= k; ++j){
dp[i][j] = (dp[i][j-1] + dp[i-1][j]) % mod;
if(j - i >= 0){
dp[i][j] = (dp[i][j] - dp[i-1][j-i] + mod) % mod;
}
}
}
return dp[n][k];
}
};