64.Minimum Path Sum

64.Minimum Path Sum

思路:
class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        int m = grid.size();
        int n = grid[0].size();
        vector<vector<int>>memory(m,vector<int>(n,-1));
        return dfs(grid,m-1,n-1,memory);
    }
    int dfs(vector<vector<int>>& grid,int m,int n,vector<vector<int>>& memory){
        if(m < 0 || n < 0) return INT_MAX;
        if(m == 0 && n == 0) return grid[0][0];
        if(memory[m][n] != -1) return memory[m][n];
        else{
            return memory[m][n] = grid[m][n] + min(dfs(grid,m-1,n,memory),dfs(grid,m,n-1,memory));
        }
    }
};
  • DP。
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,1000));   
        dp[0][0] = grid[0][0];
        for(int i = 1; i < m; i++){
            dp[i][0] = grid[i][0] + dp[i-1][0];
        }
        for(int i = 1; i < n; i++){
            dp[0][i] = grid[0][i] + dp[0][i-1];
        }
        for(int i = 1; i < m; i++){
            for(int j = 1; j < n;j++){
                dp[i][j] = grid[i][j] + min(dp[i][j-1],dp[i-1][j]);
            }
        }
        return dp[m-1][n-1];
    }
};
posted @ 2017-06-10 23:14  UniMilky  阅读(180)  评论(0编辑  收藏  举报