Minimum Path Sum
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
1 public class Solution { 2 public int minPathSum(int[][] grid) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 //[m,n] = (m,n) + min([m-1,n],[m,n-1]) 6 //only can move right or down 7 if(grid == null || grid.length == 0 || grid[0].length == 0)return 0; 8 int m = grid.length; 9 int n = grid[0].length; 10 int[][] map = new int[m][n]; 11 for(int i = 0; i < m; i ++){ 12 map[i][0] = grid[i][0]; 13 if(i > 0) map[i][0] += map[i - 1][0]; 14 } 15 for(int j = 1; j < n; j ++){ 16 map[0][j] = map[0][j - 1] + grid[0][j]; 17 } 18 for(int i = 1; i < m; i ++){ 19 for(int j = 1; j < n; j ++){ 20 map[i][j] = grid[i][j] + Math.min(map[i - 1][j], map[i][j - 1]); 21 } 22 } 23 return map[m - 1][n - 1]; 24 } 25 }
第二遍:
1 public class Solution { 2 public int minPathSum(int[][] grid) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 //[m,n] = (m,n) + min([m-1,n],[m,n-1]) 6 //only can move right or down 7 if(grid == null || grid.length == 0 || grid[0].length == 0)return 0; 8 int m = grid.length; 9 int n = grid[0].length; 10 int[][] map = new int[m][n]; 11 for(int i = 0; i < m; i ++){ 12 for(int j = 0; j < n; j ++){ 13 map[i][j] = grid[i][j]; 14 if(i > 0 && j > 0) map[i][j] += Math.min(map[i - 1][j], map[i][j - 1]); 15 else if(i > 0) map[i][j] += map[i - 1][j]; 16 else if(j > 0) map[i][j] += map[i][j - 1]; 17 } 18 } 19 return map[m - 1][n - 1]; 20 } 21 }
第三遍:
1 public class Solution { 2 public int minPathSum(int[][] grid) { 3 if(grid == null || grid.length == 0 || grid[0].length == 0) return 0; 4 int m = grid.length, n = grid[0].length; 5 int[][] result = new int[m][n]; 6 result[0][0] = grid[0][0]; 7 for(int i = 0; i < m; i ++) 8 for(int j = 0; j < n; j ++) 9 if(i != 0 || j != 0){ 10 int aa = i > 0 ? result[i - 1][j] : Integer.MAX_VALUE; 11 int bb = j > 0 ? result[i][j - 1] : Integer.MAX_VALUE; 12 result[i][j] = Math.min(aa, bb) + grid[i][j]; 13 } 14 return result[m - 1][n - 1]; 15 } 16 }
posted on 2013-10-03 03:16 Step-BY-Step 阅读(199) 评论(0) 编辑 收藏 举报