leetcode-64. 最小路径和

 

leetcode-64. 最小路径和

 

和62题不同路径一样,使用dfs方法同样超时。

class Solution {
public:
    vector<int> res;
    int minPathSum(vector<vector<int>>& grid) {
        int m = grid.size(); 
        int n = grid[0].size();
        vector<vector<bool>> visited(m, vector<bool>(n,false));
        path(grid,visited,0,0,0);
        sort(res.begin(), res.end());

        return res[0];
    }
    void path(vector<vector<int>> grid,vector<vector<bool>> visited,int i, int j, int sum){
        // int temp = sum;
        int m = grid.size(); 
        int n = grid[0].size();
        if(i<0||i>=m||j<0||j>=n||visited[i][j])
            return;
        if(i==m-1&&j==n-1){
            sum = sum + grid[i][j];
            res.push_back(sum);
            return;
        }
        sum = sum + grid[i][j];
        visited[i][j] = true;
        path(grid, visited,i,j+1,sum);
        path(grid, visited,i+1,j,sum);
        visited[i][j] = false;  // 复原
    }
};

 动态规划:

// class Solution {
// public:
//     vector<int> res;
//     int minPathSum(vector<vector<int>>& grid) {
//         int m = grid.size(); 
//         int n = grid[0].size();
//         vector<vector<bool>> visited(m, vector<bool>(n,false));
//         path(grid,visited,0,0,0);
//         sort(res.begin(), res.end());

//         return res[0];
//     }
//     void path(vector<vector<int>> grid,vector<vector<bool>> visited,int i, int j, int sum){
//         // int temp = sum;
//         int m = grid.size(); 
//         int n = grid[0].size();
//         if(i<0||i>=m||j<0||j>=n||visited[i][j])
//             return;
//         if(i==m-1&&j==n-1){
//             sum = sum + grid[i][j];
//             res.push_back(sum);
//             return;
//         }
//         sum = sum + grid[i][j];
//         visited[i][j] = true;
//         path(grid, visited,i,j+1,sum);
//         path(grid, visited,i+1,j,sum);
//         visited[i][j] = false;  // 复原
//         //sum = sum - grid[i][j];
//     }
// };



class Solution {
public:
    vector<int> res;
    int minPathSum(vector<vector<int>>& grid) {
        int m = grid.size();
        int n = grid[0].size();
        vector<vector<int>> dp(m, vector<int>(n,0));
        
        // base case
        dp[0][0] = grid[0][0];
        for(int i = 1; i < m; i++){
            dp[i][0] = dp[i-1][0] + grid[i][0];
        }
        for(int j = 1; j < n; j++){
            dp[0][j] = dp[0][j-1] + grid[0][j];
        }

        for(int i = 1; i < m; i++){
            for(int j = 1; j < n; j++){
                dp[i][j] = min(dp[i-1][j],dp[i][j-1]) + grid[i][j];
            }
        }
        return dp[m-1][n-1];
    }

};

 

上一篇:数据结构之图的遍历


下一篇:岛屿的数量