leetcode 62. Unique Paths 、63. Unique Paths II

62. Unique Paths

class Solution {
public:
    int uniquePaths(int m, int n) {
        if(m <= 0 || n <= 0)
            return 0;
        vector<vector<int> > dp(m,vector<int>(n));
        dp[0][0] = 1;
        for(int i = 1;i < m;i++)
            dp[i][0] = 1;
        for(int i = 1;i < n;i++)
            dp[0][i] = 1;
        for(int i = 1;i < m;i++){
            for(int j = 1;j < n;j++){
                dp[i][j] = dp[i-1][j] + dp[i][j-1];
            }
        }
        return dp[m - 1][n - 1];
    }
};

 63. Unique Paths II

leetcode的例子中int会越界,所以需要用long

与Unique Paths I不同在于多了障碍物,障碍物的情况直接为0就好,在初始化的时候需要做这个操作,在dp的迭代过程中也要做,其他与Unique Paths I 是一样的

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        int m = obstacleGrid.size();
        if(m <= 0)
            return 0;
        int n = obstacleGrid[0].size();
        if(n <= 0)
            return 0;
        if(obstacleGrid[0][0] == 1 || obstacleGrid[m-1][n-1] == 1)
            return 0;
        vector<vector<long> > dp(m,vector<long>(n));
        dp[0][0] = 1;
        for(int i = 1;i < m;i++){
            if(dp[i-1][0] == 0 || obstacleGrid[i][0] == 1)
                dp[i][0] = 0;
            else
                dp[i][0] = 1;
        }
        for(int i = 1;i < n;i++){
            if(dp[0][i-1] == 0 || obstacleGrid[0][i] == 1)
                dp[0][i] = 0;
            else
                dp[0][i] = 1;
        }
        for(int i = 1;i < m;i++){
            for(int j = 1;j < n;j++){
                if(obstacleGrid[i][j] == 1)
                    dp[i][j] = 0;
                else
                    dp[i][j] = dp[i-1][j] + dp[i][j-1];
            }
        }
        return dp[m-1][n-1];
    }
};

 

posted @ 2019-04-14 21:34  有梦就要去实现他  阅读(227)  评论(0编辑  收藏  举报