[LeetCode]: 64: 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.
思路:动态规划
整个序列的最小路径= 上一个节点的最小路径+当前路径的节点值
依次往前看,第一个点的最小序列等于其本身
代码:
public int minPathSum(int[][] grid) { if(grid.length == 0){ return 0; } int[][] intResult = new int[grid.length][grid[0].length]; for(int i = 0;i<grid.length;i++){ for(int j = 0;j<grid[i].length;j++){ if(i==0 && j==0){ intResult[i][j] = grid[i][j]; }else if(i == 0 && j!=0){ intResult[i][j] = intResult[i][j-1] + grid[i][j]; } else if(j== 0 && i!= 0){ intResult[i][j] = intResult[i-1][j] + grid[i][j]; } else{ int intX = intResult[i][j-1] + grid[i][j]; int intY = intResult[i-1][j] + grid[i][j]; if(intX > intY){ intResult[i][j] = intY; } else{ intResult[i][j] = intX; } } } } return intResult[grid.length-1][grid[0].length-1]; }