1 package coding; 2 3 /** 4 * Created by sakura on 2018/3/18. 5 */ 6 public class Solution187 { 7 public static void main(String[] args) { 8 int[][] array={{1,3,5,9},{8,1,3,4},{5,0,6,1},{8,8,4,0}}; 9 System.out.println(minPathSum1(array)); 10 System.out.println(minPathSum2(array)); 11 } 12 13 //时间复杂度O(M*N),空间复杂度O(M*N) 14 public static int minPathSum1(int[][] m){ 15 if(m==null||m.length==0||m[0]==null||m[0].length==0){ 16 return 0; 17 } 18 int row=m.length; 19 int col=m[0].length; 20 int[][] dp=new int[row][col]; 21 dp[0][0]=m[0][0]; 22 23 for(int i=1;i<row;i++){ 24 dp[i][0]=dp[i-1][0]+m[i][0]; 25 } 26 for(int j=1;j<col;j++){ 27 dp[0][j]=dp[0][j-1]+m[0][j]; 28 } 29 for(int i=1;i<row;i++){ 30 for(int j=1;j<col;j++){ 31 dp[i][j]=Math.min(dp[i-1][j],dp[i][j-1])+m[i][j]; 32 } 33 } 34 return dp[row-1][col-1]; 35 } 36 37 //空间压缩,时间复杂度O(M*N),空间复杂度O(min{M,N}) 38 public static int minPathSum2(int[][] m){ 39 if(m==null||m.length==0||m[0]==null||m[0].length==0){ 40 return 0; 41 } 42 int more=Math.max(m.length,m[0].length); 43 int less=Math.min(m.length,m[0].length); 44 boolean rowmore=more==m.length; 45 int[] arr=new int[less]; 46 arr[0]=m[0][0]; 47 48 for(int i=1;i<less;i++){ 49 arr[i]=arr[i-1]+(rowmore?m[0][i]:m[i][0]); 50 } 51 for(int i=1;i<more;i++){ 52 arr[0]=arr[0]+(rowmore?m[i][0]:m[0][i]); 53 for(int j=1;j<less;j++){ 54 arr[j]=Math.min(arr[j-1],arr[j]) 55 +(rowmore?m[i][j]:m[j][i]); 56 } 57 } 58 return arr[less-1]; 59 } 60 }