Given two integers n and k, find how many different arrays consist of numbers from 1 to n such that there are exactly kinverse 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
nis in the range [1, 1000] andkis in the range [0, 1000].
解题思路:
假设dp[n][k]为1-n个数字组成的数组中逆序为k的数组个数。
那么当dp[n-1][k]时,n应放位置如下:
x1 , x2 , x3 ,..........,xn-1, n
当dp[n-1][k - 1]时,n应放位置为:
x1,x2,x3,..........,xn-2,n,xn-1 增加n,xn-1这一对逆序;
依次类推 : 将n放在x1前面时最多能增加n-1对逆序 ;
所以
当k>=n时
dp[n][k] = dp[n-1][k] + dp[n-1][k-1]+....+dp[n-1][k-n+1];
dp[n][k-1] = dp[n-1][k-1] + dp[n-1][k-2] +......+ dp[n-1][k-n];
所以dp[n][k] = dp[n-1][k] + dp[n][k-1] - dp[n-1][k-n];
当k<n时:
dp[n][k] = dp[n-1][k] + dp[n-1][k-1]+....+dp[n-1][0];
dp[n][k-1] = dp[n-1][k-1] + dp[n-1][k-2] + dp[n-1][0];
所以dp[n][k] = dp[n-1][k] + dp[n][k-1] ;
class Solution {
public:
int kInversePairs(int n, int k) {
vector<vector<int>> dp(n + 1 , vector<int>(k + 1 , 0)) ;
for(int i = 0 ; i <= n ; ++i) dp[i][0] = 1 ;
int mod = 1000000007 ;
for(int i = 1 ; i<= n ; ++i)
for(int j = 1 ; j<= k ; ++j)
{
dp[i][j] = (dp[i - 1][j] + dp[i][j - 1])% mod ;
if(j >= i) dp[i][j] = (dp[i][j] - dp[i - 1][j - i] + mod)%mod ;
}
//cout<<dp[3][0]<<endl;
return dp[n][k] ;
}
};

本文探讨了在由1到n的整数构成的数组中,寻找含有k个逆序对的不同数组数量的问题。通过定义逆序对的概念,即对于数组中的元素a[i]和a[j],如果i<j且a[i]>a[j],则构成一对逆序对。文章提出了一种动态规划的解题策略,利用dp[n][k]表示由1到n的数字组成且包含k个逆序对的数组个数,详细阐述了递推公式及其实现过程。

被折叠的 条评论
为什么被折叠?



