您的位置:首页 > 大数据 > 人工智能

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];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: