package com.hzins.suanfa; import org.junit.Test; public class JuzhenMinVarSum { /** * 空间复杂度o(n^2) * 时间复杂度o(n^2) * @param array * @return */ public static int[][] getdp(int[][] array){ int[][] dp = new int[array.length][array[0].length]; dp[0][0] = array[0][0]; for(int i = 1 ;i < array.length;i ++){ dp[i][0] = array[i][0] + dp[i-1][0]; } for(int i = 1;i< array[0].length;i ++){ dp[0][i] = array[0][i] + dp[0][i -1]; } for(int i = 1;i < array.length;i ++){ for(int j = 1; j<array[0].length;j++){ dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + array[i][j]; } } return dp; } /** * 空间复杂度O(n) * 时间复杂度o(n^2) * @param array * @return */ public static int[] getdp1(int[][] array){ int[] dp = new int[array[0].length]; dp[0] = array[0][0]; for(int i =1;i<array[0].length;i++){ dp[i] = array[0][i] + dp[i - 1]; } for(int i = 1; i < array.length;i++){ dp[0] = array[i][0] + dp[0]; for (int j = 1;j < array[0].length;j ++){ int min = Math.min(dp[j], dp[j - 1]); dp[j] = min + array[i][j]; } } return dp; } public static void printJuzhen(int[][] a){ for(int i = 0;i< a.length;i++){ for (int j = 0;j < a[0].length;j ++){ System.out.print(a[i][j] + " "); } System.out.println(); } } @Test public void test(){ int[][] a = new int[3][5]; for(int i = 0;i < a.length;i ++){ a[i][0] = 3; a[i][1] = 4; a[i][2] = 7; a[i][3] = 4; a[i][4] = 2; } printJuzhen(a); System.out.print(" "); int[] dp = getdp1(a); for(int i : dp){ System.out.print(i + " "); } } @Test public void test1(){ int[][] a = new int[3][5]; for(int i = 0;i < a.length;i ++){ a[i][0] = 3; a[i][1] = 4; a[i][2] = 7; a[i][3] = 4; a[i][4] = 2; } printJuzhen(a); System.out.println(" "); int[][] dp = getdp(a); printJuzhen(dp); } }