K Inverse Pairs Array
2017-11-22 21:07
417 查看
问题来源
问题描述
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:
1. The integer n is in the range [1, 1000] and k is in the range [0, 1000].
问题分析
动规类问题实际最重要的就是找到解题的思路。对于此题,说实话一开始是无从下手,然后去参考了别人的博文:dp[n][k] denotes the number of arrays that have k inverse pairs for array composed of 1 to n we can establish the recursive relationship between dp[n][k] and dp[n-1][i]: if we put n as the last number then all the k inverse pair should come from the first n-1 numbers if we put n as the second last number then there's 1 inverse pair involves n so the rest k-1 comes from the first n-1 numbers ... if we put n as the first number then there's n-1 inverse pairs involve n so the rest k-(n-1) comes from the first n-1 numbers dp[n][k] = dp[n-1][k]+dp[n-1][k-1]+dp[n-1][k-2]+...+dp[n-1][k+1-n+1]+dp[n-1][k-n+1]
中文大意就是根据n放的位置来计算放置n后多的反序对个数,最后相加即可。看到这,我们其实也就可以动手做题了。、
解决代码
class Solution { public: int kInversePairs(int n, int k) { vector<vector<long>> dp(n + 1, vector<long>(k+1, 0)); dp[0][0] = 1; int mod = pow(10, 9) + 7; for(int i = 1; i <= n; ++i) { for(int j = 0; j <= k; ++j) { for(int m = 0; m < i; ++m) { if(j - m >= 0) { dp[i][j] = (dp[i][j] + dp[i-1][j-m]); } } dp[i][j] %= mod; } } return dp [k]; } };
相关文章推荐
- leetcode 629. K Inverse Pairs Array
- leetcode:K inverse pairs array
- 629. K Inverse Pairs Array 自制答案
- 629. K Inverse Pairs Array
- [Leetcode] 629. K Inverse Pairs Array 解题报告
- [LeetCode] K Inverse Pairs Array K个翻转对数组
- K Inverse Pairs Array (leetcode)
- 629. K Inverse Pairs Array
- Leetcode | K Inverse Pairs Array
- 629. K Inverse Pairs Array
- [leetcode]629. K Inverse Pairs Array
- 629. K Inverse Pairs Array
- K Inverse Pairs Array - LeetCode
- Leetcode 532. K-diff Pairs in an Array(Easy)
- K-diff Pairs In An Array
- Leetcode 532. K-diff Pairs in an Array
- Counting Inversion Pairs in an Array
- LeetCode-algorithms 532. K-diff Pairs in an Array
- [LeetCode] 532. K-diff Pairs in an Array
- LeetCode 532. K-diff Pairs in an Array (在数组中相差k的配对)