原题:
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 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].
思路:这是一道动态规划的题目。用dp[n][k]代表n个数(1-n)任意全排列中存在k对逆序数对的排列的数量总数。可以看到,例子中,n = 3, k = 1的情况下,共有[1,3,2], [2,1,3]两种可能; n = 3, k = 0的情况下,有[1,2,3]一种可能。如果有动态规划的思维,这时我们自然会想,n=4, k=1的情况呢?这种情况涉及到4这个数字怎么放的问题。 n = 3, k = 0这种情况中,把4放在[1,2,3],共有4个位置可以放,但只有[1,2,4,3]符合要求。依次类推,n = 3, k = 1这种情况下,4只有放在最后才符合要求,即[1,3,2,4], [2,1,3,4]。所以n=4, k=1与n = 3, k = 0和n = 3, k = 0有关。继续想下去,我们会想到dp[n][k]是不是与sum(dp[n-1][i] (i=0,1,…,k))都有关呢?dp[n][k]与dp[n][k-1]又有什么关系呢?按照思路想下去,可以推出如下代码给出的递推方程。当然,本题有不少的坑,代码中均有一一注明。
代码:
classSolution {public:
int kInversePairs(int n, int k) {
intmod=1000000007;
int dp[n+1][k+1];
memset(dp,0,sizeof(dp));
//初始化for(int i=1;i<=n;i++){
dp[i][0]=1;
}
for(int i=1;i<=n;i++){
//n=5时,只有[5,4,3,2,1],共有(1+4)*4/2 =10个逆序,这是最极端的情况//j<=k是题目要求只算到k,由于题目的计算只与小于k的情况有关,所以大于k的情况不用算for(int j=1;j<=min(k,(1+(i-1))*(i-1)/2);j++){
if(j>=i){
dp[i][j]=(dp[i][j-1]+dp[i-1][j]-dp[i-1][j-i])%mod;
//之所以加上这句判断,是因为本来必然有dp[i][j-1]>dp[i-1][j-i],但由于模除的原因,可能dp[i][j-1]变得更小了//这导致了kInversePairs(1000,1000)的样例出错,坑了我很久
dp[i][j]=(dp[i][j-1]-dp[i-1][j-i])<0?(dp[i][j]+mod)%mod:dp[i][j];
}
else
dp[i][j]=(dp[i][j-1]+dp[i-1][j])%mod;
}
}
return dp[n][k];
}
};