63. Unique Paths II 動態規劃

description:

https://leetcode.com/problems/unique-paths/
機器人從一堆方格的左上角走到右下角,只能往右或者往下走 ,問有幾種走法,這個加了難度,在矩陣中加了障礙物
Note:code

Example:ip

Example 1:

Input:
[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]
Output: 2
Explanation:
There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right

answer:

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        if (obstacleGrid.empty() || obstacleGrid[0].empty() || obstacleGrid[0][0] == 1) return 0;
        int m = obstacleGrid.size(), n = obstacleGrid[0].size();
        vector<vector<long>> dp(m + 1, vector<long>(n + 1, 0)); //比實際大一圈是爲了處理左邊和上邊兩個邊的邊緣問題
        dp[0][1] = 1; // 初始化
        for (int i = 1; i <= m; ++i) {
            for (int j = 1; j <= n; ++j) {
                if (obstacleGrid[i - 1][j - 1] != 0) continue; //若是是障礙則略過
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
            }
        }
        return dp[m][n];
    }
};

relative point get√:

hint :

動態規劃leetcode

相關文章
相關標籤/搜索