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] andk
is in the range [0, 1000].
Notes:
The question can be solved by dp.
Let dp[i][j] represents the number of arrays with the the first i numbers with j inverse pairs.
Then,
dp[i][j] = dp[i-1][j] + dp[i-1][j-1] + ... + dp[i-1][j - (i-1)]
The first term on the left means we place the ith element in the last position;
The second term means that we place the ith element in the second last position;
...;
The last term means that we place the ith element in the first position.
One improvement is that we can use a sum to memorize the sum of the previous dp[i-1][j], ... dp[i-1][j-(i-1)], which essentially is a "sliding window" sum. This improvement can reduce the time complexity from O(NK^2) to O(NK).
See the code below:
class Solution { public: int kInversePairs(int n, int k) { vector<vector<long>> dp(n+1, vector<long>(k+1, 0)); dp[0][0] = 1; // for(int i=0; i<=n; ++i) dp[i][0] = 1; int mod = 1e9+7; for(int i=1; i<=n; ++i) { long sum = 0; for(int j=0; j<=k; ++j) { sum += dp[i-1][j] % mod; if(j>i-1) sum = (sum - dp[i-1][j-i] + mod) % mod; dp[i][j] = sum % mod; } } return dp[n][k]; } };
No comments:
Post a Comment