leetcode 64. Minimum Path Sum

Posted LaplaceAkuir

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

采用动态规划的方法,dp[i][j] = min(dp[i-1][j],dp[i],[j-1])+a[i][j];

 1 class Solution {
 2 public:
 3     int minPathSum(vector<vector<int>>& grid) {
 4         int m = grid.size();
 5         int n = grid[0].size();
 6         vector<vector<int> > dp(m,vector<int>(n));
 7         for(int i = 0;i < m;i++){
 8             for(int j = 0;j < n ;j++){
 9                 if(i == 0){
10                     if(j == 0){//初始化
11                          dp[i][j] = grid[i][j];
12                     }
13                     else{//i==0 && j!=0
14                         dp[i][j] = dp[i][j-1]+grid[i][j];
15                     }
16                 }
17                 else if(j == 0){//i!=0&& j==0
18                     dp[i][j] = dp[i-1][j] + grid[i][j];
19                 }
20                 else{//i,j!=0
21                     dp[i][j] = min(dp[i-1][j],dp[i][j-1])+grid[i][j];
22                 }
23                 
24             }
25         }
26         return dp[m-1][n-1];
27     }
28 };

 

以上是关于leetcode 64. Minimum Path Sum的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode64 Minimum Path Sum

Leetcode64 Minimum Path Sum

[leetcode-64-Minimum Path Sum]

LeetCode 64. Minimum Path Sum

leetcode 64. Minimum Path Sum

LeetCode64 Minimum Path Sum