# LeetCode-64. 最小路径和

[[1,3,1],
[1,5,1],
[4,2,1]
]

## 思路

[1,3,1]
[1,5,1]
[4,2,1]

dp(0,0) = grid(0,0) + min(dp(1,0),dp(0,1))

## 一般递归解法

class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
return minPathSumRecusion(grid, 0, 0);
}
private:
int minPathSumRecusion(vector<vector<int>>& grid, int m, int n){
if(grid.size() == 0)
return 0;

if(m == grid.size()-1 && n == grid[0].size()-1)
return grid[m][n];

if(m == grid.size()-1)
return grid[m][n]+minPathSumRecusion(grid,m,n+1);

if(n == grid[0].size()-1)
return grid[m][n]+minPathSumRecusion(grid,m+1,n);

return grid[m][n]+ min(minPathSumRecusion(grid,m+1,n), minPathSumRecusion(grid,m,n+1));
}
};


## 记忆化搜索递归

• grid为0的情况
• 下一步只能往右的情况
• 下一步只能往下的情况
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
if(grid.size() == 0)
return 0;
int m = grid.size();
int n = grid[0].size();
m_memo = vector<vector<int>>(m+1,vector<int>(n+1,0));
//初始化边界情况
for(int i = n-1; i >= 0;--i)
m_memo[m-1][i] = grid[m-1][i] + m_memo[m-1][i+1];
for(int j = m-1; j >= 0;--j)
m_memo[j][n-1] = grid[j][n-1] + m_memo[j+1][n-1];

return minPathSumRecusion(grid, 0, 0);
}
private:
int minPathSumRecusion(vector<vector<int>>& grid, int m, int n){

if(grid.size() == 0)
return 0;

if(m_memo[m][n] != 0)
{
return m_memo[m][n];
}

if(m == grid.size()-1 && n == grid[0].size()-1)
{
m_memo[m][n] = grid[m][n];
return m_memo[m][n];
}

if(m == grid.size()-1)
{
return m_memo[m][n];
}

if(n == grid[0].size()-1)
{
return m_memo[m][n];
}

m_memo[m][n] = min(grid[m][n]+minPathSumRecusion(grid,m+1,n), grid[m][n]+minPathSumRecusion(grid,m,n+1));
return m_memo[m][n];
}
vector<vector<int>> m_memo;
};


## 动态规划

class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
if(grid.size() == 0)
return 0;
int m = grid.size();
int n = grid[0].size();
m_memo = vector<vector<int>>(m+1,vector<int>(n+1,0));
//初始化边界情况
for(int i = n-1; i >= 0;--i)
m_memo[m-1][i] = grid[m-1][i] + m_memo[m-1][i+1];
for(int j = m-1; j >= 0;--j)
m_memo[j][n-1] = grid[j][n-1] + m_memo[j+1][n-1];

for(int i = m-2; i >= 0;--i)
{
for(int j = n-2; j >= 0;--j)
{
m_memo[i][j] = grid[i][j] + min(m_memo[i][j+1], m_memo[i+1][j]);
}
}
return m_memo[0][0];
}
};

posted @ 2018-07-04 01:12  Blue影  阅读(1262)  评论(0编辑  收藏  举报