动态规划算法-数组连续和为k的前后索引

 

    public static int a() {
        int target = 6;
        int[] a = {3, 3, 1, 3, 3, 7, -1};
        int[] dp = new int[a.length + 1];
        //初始化
        dp[0] = 0;
        for (int i = 1; i < dp.length; i++) {
            dp[i] = dp[i - 1] + a[i - 1];
        }
        System.out.println(JSON.toJSONString(dp));

        //状态转移方程
        for (int i = 1; i < dp.length; i++) {
            for (int j = 0; j < i; j++) {
                if (dp[i] - dp[j] == target) {
                    //输出符合要求索引
                    System.out.println(j + "--" + (i - 1));
                }
            }
        }

        return -1;
    }

 

posted @ 2020-07-14 10:42  使用D  阅读(218)  评论(0编辑  收藏  举报