Given two integers
n
andk
, find how many different arrays consist of numbers from1
ton
such that there are exactlyk
inverse pairs.We define an inverse pair as following:Forith
andjth
element in the array, ifi
<j
anda[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].
时间复杂度O(nk),空间复杂度O(nk)。
解题思路:
用二维数组 v[i][j] 表示长度为 j ,逆对数量为 i 的数组的个数。
假如有这样一个数组: 【3, 2, 4, 1】 ----- 逆对有 4
那么在其中插入数字 5 之后可能得到的数组有: 【5, 3, 2, 4, 1】 ----- 逆对有 4 + 4
【3,5, 2, 4, 1】 ----- 逆对有 4 + 3
【3, 2,5, 4, 1】 ----- 逆对有 4 + 2
【3, 2, 4,5, 1】 ----- 逆对有 4 + 1
【3, 2, 4, 1,5】 ----- 逆对有 4 + 0
同理,和【3, 2, 4, 1】具有相同逆对的【3, 4, 2, 1】在插入数字 5 之后同样具有以上的规律,因为 5 最大,所以在数字 5 之后的数字和 5 配对时一定是逆对。
那么得到以下式子:
v[i][j] = v[i][j-1] +
v[i-1][j-1] +
......
v[i-j+1][j-1]. ( i-j+1 >= 0)
加到第 i-j+1 项的原因是长度是 j-1 的数组插入数字 j 后最多只能增加 j-1 个逆对,所以要得到逆对数是 i 的数组数,最短可以从长度是 i-(j-1)=i-j+1 的数组插入数字 j 而得到( j 放在最前面)。
本来得到上面的式子就可以用动态规划去解题了,但是此时时间复杂度是 O(n^2 * k)。其实可以通过相似的式子想减而把时间复杂度降低。
同理 v[i-1][j] = v[i-1][j-1] +
v[i-2][j-1] +
......
v[i-j][j-1]. ( i-j >= 0)
由上面两个式子想减可以得出:
v[i][j] = v[i-1][j] + v[i][j-1] - v[i-j][j-1].
代码:
int kInversePairs(int n, int k) { if (n < 0 || k < 0) return -1; long mod = 1000000007; vector<vector<long> > v(k+1, vector<long>(n+1, 0)); int i, j, tmp; for (i = 0; i <= n; ++i) { v[0][i] = 1; } for (i = 1; i <= k; ++i) { for (j = 1; j <= n; ++j) { tmp = i - j; v[i][j] = v[i-1][j] + v[i][j-1]; if (v[i][j] >= mod) v[i][j] -= mod; if (tmp >= 0) { v[i][j] += mod; v[i][j] -= v[tmp][j-1]; } if (v[i][j] >= mod) v[i][j] -= mod; } } return v[k][n]; }