Unique Paths II (LeetCode)

Question:

https://oj.leetcode.com/problems/unique-paths-ii/

 

跟Unique Paths一样,DP方法。不同的是如果obstacleGrid是1,paths需要设为0.

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;
        
     vector<int> paths(n, 0);
     
     for (int i = 0; i < m; i++)
     {
         for (int j = 0; j < n; j++)
         {
             if (obstacleGrid[i][j] == 1)
             {
                paths[j] = 0;
                continue;
             }
             
             if (i == 0)
             {
                 paths[j] = j > 0 ? paths[j-1] : 1;
             }
             else
             {
                 paths[j] += (j > 0 ? paths[j-1] : 0);
             }
         }
       }
       
       return paths[n-1];
    }
};

 

posted @ 2015-01-23 15:05  smileheart  阅读(104)  评论(0)    收藏  举报