1995. 统计特殊四元组

2021-12-30  本文已影响0人  漫行者_

虽然标记为简单题,但很难顶!!
map,需要注意遍历的顺序!!!!!

  public int countQuadruplets(int[] nums) {
        int[] count = new int[1020];
        int res = 0;
        for (int i = nums.length - 3; i >= 1; i--) {
            for (int p = i+2; p < nums.length; p++) {
                count[nums[p] - nums[i+1] + 200]++;
            }
            for (int q = 0; q < i; q++) {
                res += count[nums[q] + nums[i] + 200];
            }
        }
        return res;
    }

动态规划

class Solution {
    public int countQuadruplets(int[] nums) {
        int n = nums.length;
        int[][][] f = new int[n + 1][110][4];
        f[0][0][0] = 1;
        for (int i = 1; i <= n; i++) {
            int t = nums[i - 1];
            for (int j = 0; j < 110; j++) {
                for (int k = 0; k < 4; k++) {
                    f[i][j][k] += f[i - 1][j][k];
                    if (j - t >= 0 && k - 1 >= 0) f[i][j][k] += f[i - 1][j - t][k - 1];
                }
            }
        }
        int ans = 0;
        for (int i = 3; i < n; i++) ans += f[i][nums[i]][3];
        return ans;
    }
}

上一篇下一篇

猜你喜欢

热点阅读