1. 程式人生 > >LeetCode 64. Minimum Path Sum(最小和的路徑)

LeetCode 64. Minimum Path Sum(最小和的路徑)

turn paths [0 solution 返回 資料 lan 需要 i++

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.


題目標簽:Array

  這道題目和前面兩題差不多,基本思想都是一樣的。這題要求我們找到最小和的路徑。同樣用Dynamic programming,我們可以分析一下,path 只能走右邊和下面,那麽對於每一個點,它的path 只可能從左邊和上面來,我們只要在兩者中取一個小的加上自己就可以了。因此,遍歷gird,對於每一個點,有四種情況:

  case 1:它有left 和top,取小的加上自己;

  case 2:它只有left,left + 自己;

  case 3:它只有top, top + 自己;

  case 4:它沒有left 和top,什麽都不需要做。

  最後返回終點的值就可以了。這裏可以in-place, 也可以自己新建立一個matrix。

Java Solution:

Runtime beats 35.80%

完成日期:07/22/2017

關鍵詞:Array

關鍵點:Dynamic Programming, 逆向思考

 1 public class Solution 
 2 {
 3     public
int minPathSum(int[][] grid) 4 { 5 int rowSize = grid.length; 6 int colSize = grid[0].length; 7 8 9 for(int i=0; i<rowSize; i++) // row 10 { 11 for(int j=0; j<colSize; j++) // column 12 { 13 // if this point has both left and top
14 if(j-1 >=0 && i-1 >=0) 15 grid[i][j] += Math.min(grid[i][j-1], grid[i-1][j]); 16 else if(j-1 >=0) // if this point only has left 17 grid[i][j] += grid[i][j-1]; 18 else if(i-1 >=0) // if this point only has top 19 grid[i][j] += grid[i-1][j]; 20 // else, this point has no left and no top 21 22 } 23 } 24 25 return grid[rowSize-1][colSize-1]; 26 } 27 }

參考資料:N/A

LeetCode 算法題目列表 - LeetCode Algorithms Questions List

LeetCode 64. Minimum Path Sum(最小和的路徑)