2021.11.11 - 146.K个逆序对数组

1. 题目

在这里插入图片描述

2. 思路

(1) 动态规划

  • 过于复杂,建议背诵默写。

3. 代码

public class Test {
    
    
    public static void main(String[] args) {
    
    
    }
}

class Solution {
    
    
    public int kInversePairs(int n, int k) {
    
    
        final int MOD = 1000000007;
        int[][] dp = new int[2][k + 1];
        dp[0][0] = 1;
        for (int i = 1; i <= n; i++) {
    
    
            for (int j = 0; j <= k; j++) {
    
    
                int cur = i & 1;
                int pre = cur ^ 1;
                dp[cur][j] = (j - 1 >= 0 ? dp[cur][j - 1] : 0) - (j - i >= 0 ? dp[pre][j - i] : 0) + dp[pre][j];
                if (dp[cur][j] >= MOD) {
    
    
                    dp[cur][j] -= MOD;
                } else if (dp[cur][j] < 0) {
    
    
                    dp[cur][j] += MOD;
                }
            }
        }
        return dp[n & 1][k];
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44021223/article/details/121268926