首页 > 代码库 > 61. Unique Paths && Unique Paths II

61. Unique Paths && Unique Paths II

Unique Paths

A robot is located at the top-left corner of a m x n grid (marked ‘Start‘ in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish‘ in the diagram below).

How many possible unique paths are there?

Above is a 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

思路: 其实答案就是 C(m+n-2, m-1). 但是写程序利用动态规划会简单快捷。(给两个代码,第一个方便理解,第二个是基于第一个的优化)

1.

class Solution { // C(m+n-2, m-1)public:    int uniquePaths(int m, int n) {        vector<vector<int> > times(m, vector<int>(n, 0));        for(int r = 0; r < m; ++r) times[r][0] = 1;        for(int c = 1; c < n; ++c) times[0][c] = 1; // 只能到 1 次        for(int r = 1; r < m; ++r)             for(int c = 1; c < n; ++c)                 times[r][c] = times[r-1][c] + times[r][c-1];        return times[m-1][n-1];    }};

 2.

class Solution { // C(m+n-2, m-1)public:    int uniquePaths(int m, int n) {        if(m <= 0 || n <= 0) return 0;        vector<int> R(n, 1); // 一行行的记录        for(int r = 1; r < m; ++r)             for(int c = 1; c < n; ++c)                 R[c] = R[c]+ R[c-1];        return R[n-1];    }};

 

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.

思路:同上,只是最初初始化全 0 . 当前位置为 1 时,则当到达前位置的步数为 0.

class Solution {public:    int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {        if(!obstacleGrid.size() || !obstacleGrid[0].size()) return 0;        int m = obstacleGrid.size(), n = obstacleGrid[0].size();        vector<int> R(n, 0);        R[0] = 1-obstacleGrid[0][0];        for(int r = 0; r < m; ++r)             for(int c = 0; c < n; ++c) {                if(c > 0)                    R[c] = (obstacleGrid[r][c] == 1 ? 0 : (R[c] + R[c-1]));                else if(obstacleGrid[r][c] == 1) R[0] = 0;            }        return R[n-1];    }};

 

61. Unique Paths && Unique Paths II