63. Unique Paths II

題目

Follow up for "Unique Paths":

Now consider if some obstacles are added to the grids. How many unique paths would there be?

An obstacle and empty space is marked as 1 and 0 respectively in the grid.

For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.

[
[0,0,0],
[0,1,0],
[0,0,0]
]
The total number of unique paths is 2.

分析

和第62題基本一樣,不同的是在初始化時(shí)要將障礙處的路徑數(shù)置為0,且在推導(dǎo)的時(shí)候跳過(guò)這些位置。
而且也要推導(dǎo)最后兩行。

實(shí)現(xiàn)

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

思考

做這種題的時(shí)候要非常注意,條件增加時(shí)變化了的情況。如果繼續(xù)沿用之前的那種初始化最后一行和最后一列為1的情況就會(huì)出現(xiàn)問題,改成由后一個(gè)推導(dǎo)才可。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Follow up for "Unique Paths":Now consider if some obstacl...
    ShutLove閱讀 244評(píng)論 0 0
  • Follow up for "Unique Paths":Now consider if some obstacl...
    HalcyonMoon閱讀 323評(píng)論 0 0
  • Follow up for "Unique Paths": Now consider if some obstac...
    Jeanz閱讀 266評(píng)論 0 0
  • Description Follow up for "Unique Paths": Now consider if...
    Nancyberry閱讀 310評(píng)論 0 0
  • 10點(diǎn)的時(shí)候收到好友的回復(fù),因?yàn)殚L(zhǎng)期的空白她面臨詞窮的困境所以無(wú)法準(zhǔn)時(shí)給我一篇文稿,我玩笑式的回復(fù)好友,不會(huì)第二天...
    素與舒閱讀 329評(píng)論 0 1

友情鏈接更多精彩內(nèi)容