###### leetcode #64 in cpp

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.

Solution:

We use DP where dp[i][j] = minimum sum along the path from position(i+1,j+1) to the destination.

Then dp[i][j] = min(dp[i+1][j], dp[i][j+1]) + grid[i][j]. That is, we select the direction which gives us a smaller sum, when we decide to take the next step.

Code:

class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<vector<int>> dp(m, vector<int>(n,0));
dp[m-1][n-1] = grid[m-1][n-1];
for(int i = m-2; i >= 0; i --){//right border
dp[i][n-1] = grid[i][n-1] + dp[i+1][n-1];
}
for(int i = n-2; i >= 0; i--){//bottom border
dp[m-1][i] = grid[m-1][i]+dp[m-1][i+1];
}
for(int i = m-2; i >= 0; i --){
for(int j = n-2; j>=0; j --){
dp[i][j] = min(dp[i+1][j], dp[i][j+1])+grid[i][j];//compare results from turning right and turning down
}
}
return dp[0][0];
}
};

One optimization is to update the sum in place in grid instead of using the dp arrays. This saves us some memory.

#### LeetCode cpp最新中文题解.pdf

2018年01月10日 866KB 下载

#### 免费的LeetCode-cpp题解(C++版本)大全 pdf下载

2018年01月18日 807KB 下载

#### leetcode刷题 总结 记录 备忘 64

2015-07-27 18:28:47

2016-07-21 09:37:42

#### [C++]LeetCode: 64 Subsets II

2014-12-31 12:52:02

#### LeetCode347—Top K Frequent Elements

2016-05-03 16:20:00

#### LeetCode OJ 之 Palindrome Linked List（回文链表判断）

2015-07-14 14:16:40

#### Leetcode 283. Move Zeroes (Easy) (cpp)

2016-07-12 11:59:39

#### 刷LeetCode刷LeetCode刷LeetCode刷LeetCode

2018年01月09日 1.55MB 下载

#### leetCode 64.Minimum Path Sum (最短路) 解题思路和方法

2015-07-17 16:25:43

## 不良信息举报

leetcode #64 in cpp