You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

44 lines
911 B

package class10;
// 测试链接 : https://leetcode.com/problems/k-inverse-pairs-array/
public class Code03_KInversePairs {
public static int kInversePairs(int n, int k) {
if (n < 1 || k < 0) {
return 0;
}
int[][] dp = new int[n + 1][k + 1];
dp[0][0] = 1;
int mod = 1000000007;
for (int i = 1; i <= n; i++) {
dp[i][0] = 1;
for (int j = 1; j <= k; j++) {
dp[i][j] = (dp[i][j - 1] + dp[i - 1][j]) % mod;
if (j >= i) {
dp[i][j] = (dp[i][j] - dp[i - 1][j - i] + mod) % mod;
}
}
}
return dp[n][k];
}
public static int kInversePairs2(int n, int k) {
if (n < 1 || k < 0) {
return 0;
}
int[][] dp = new int[n + 1][k + 1];
dp[0][0] = 1;
for (int i = 1; i <= n; i++) {
dp[i][0] = 1;
for (int j = 1; j <= k; j++) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
if (j >= i) {
dp[i][j] -= dp[i - 1][j - i];
}
}
}
return dp[n][k];
}
}