最小路径和

题目链接:最小路径和

解法一:深度优先搜索

class Solution {
int sum = INT_MAX;
int m,n;
public:
    int minPathSum(vector<vector<int>>& grid) {
        m = grid.size();
        n = grid[0].size();
        DFS(0,0,0,grid);
        return sum;
    }

    void DFS(int x,int y,int num,vector<vector<int>>& grid){
        num = num + grid[x][y];
        if(num >= sum){     //剪枝操作
            return;
        }
        if(x == m-1 && y == n-1){
            if(num < sum){
                sum = num;
            }
            return;
        }
        if(x+1 < m){
            DFS(x+1,y,num,grid);
        }

        if(y+1 < n){
            DFS(x,y+1,num,grid);
        }
        
    }
};

复杂度分析

时间复杂度:
空间复杂度:O(1)

代码超时

解法二:动态规划

当i > 0 ,且 j = 0时,dp[i][0] = dp[i-1][0] + grid[i][j];
当j > 0,且 i = 0时,dp[0][j] = dp[0][j-1] + grid[i][j];
当i > 0,且j > 0 时,dp[i][j] = min(dp[i-1][j],dp[i][j-1]) + grid[i][j]

代码如下:

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        if(grid.size() == 0 || grid[0].size() == 0){
            return 0;
        }
        int r,c;
        r = grid.size();
        c = grid[0].size();

        
        vector<vector<int> > dp(r,vector<int>(c));
       
        //初始化
        dp[0][0] = grid[0][0];
        for(int i=0;i<r;i++){
            for(int j=0;j<c;j++){
                if(i == 0 && j == 0){
                    continue;
                }

                if(i == 0 && j>0){
                    dp[i][j] = dp[i][j-1] + grid[i][j];
                }else if(j == 0 && i>0){
                    dp[i][j] = dp[i-1][j] + grid[i][j];
                }else{
                    dp[i][j] = min(dp[i-1][j],dp[i][j-1]) + grid[i][j];
                }
            }
        }

        return dp[r-1][c-1];
    }
};

更为漂亮的写法


class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        if(grid.size() == 0 || grid[0].size() == 0){
            return 0;
        }
        int r,c;
        r = grid.size();
        c = grid[0].size();

        
        vector<vector<int> > dp(r,vector<int>(c));
       
        //初始化
        dp[0][0] = grid[0][0];

        //边界情况一
        for(int j=1;j<c;j++){
            dp[0][j] = dp[0][j-1] + grid[0][j];
        }

        //边界情况二
        for(int i=1;i<r;i++){
            dp[i][0] = dp[i-1][0] + grid[i][0];
        }
        for(int i=1;i<r;i++){
            for(int j=1;j<c;j++){
                dp[i][j] = min(dp[i-1][j],dp[i][j-1]) + grid[i][j];
            }
        }

        return dp[r-1][c-1];
    }
};

posted @ 2020-10-07 16:04  focusDing  阅读(95)  评论(0编辑  收藏  举报