1. 程式人生 > >leetcode 62|63. Unique Paths 1|2

leetcode 62|63. Unique Paths 1|2

62. Unique Paths


標準動態規劃,當前步只能從上面和左邊走過來。

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


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.

Note: m and n will be at most 100.

還是動態規劃,加一個條件而已

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) 
    {
        int row = obstacleGrid.size();
        int col = obstacleGrid[0].size();
        if (row > 0 && col > 0 && obstacleGrid[0][0] == 1)
            return 0;
        
        int flag = 1;
        for (int i = 0; i < row; i++)
        {
            if (flag == 1 && obstacleGrid[i][0] == 0) 
                obstacleGrid[i][0] = 1; 
            else
            {
                flag = 0;
                obstacleGrid[i][0] = 0; 
            }
        }
        flag = 1;
        for(int i = 1; i < col; i++)
        {
            if (flag == 1 && obstacleGrid[0][i] == 0) 
                obstacleGrid[0][i] = 1; 
            else
            {
                flag = 0;
                obstacleGrid[0][i] = 0; 
            }
        }
         
        for(int i = 1; i < row; i++)
            for(int j = 1; j < col; j++)
            {
                 if (obstacleGrid[i][j] == 1)
                     obstacleGrid[i][j] = 0;
                 else
                     obstacleGrid[i][j] = obstacleGrid[i-1][j] + obstacleGrid[i][j-1];
            }
        return obstacleGrid[row-1][col-1];
    }
};