Skip to content

Latest commit

 

History

History
62 lines (54 loc) · 1.38 KB

63.md

File metadata and controls

62 lines (54 loc) · 1.38 KB

63. 不同路径 II

DP

时间复杂度:O(m * n)。

空间复杂度:O(m * n)。

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

优化

时间复杂度:O(m * n)。

空间复杂度:O(n)。

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