动态规划算法-数组连续和为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; }
收藏文章数量从多到少与“把书读薄”是一个道理