LeetCode --- unique-paths-ii (path number)

Title Description

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.

Ideas:

1 1 1
1 2 3
1 3 6
1 4 10

                                                    dp [i] [j] matrix

满足   dp[i][j]=dp[i-1][j]+dp[i][j-1];(i>1&&j>1)

class Solution {
public:
    int hash[102][102]={0};
    int uniquePaths(int m, int n) {
        if(m<=0||n<=0) return -1;
        if(m==1||n==1) return 1;
        if(hash[m][n]!=0) return hash[m][n];
        hash[m][n]=uniquePaths(m,n-1)+uniquePaths(m-1,n);
        return hash[m][n];
    }
};

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

Expand topics 

Title Description

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 as1and0respectively 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 is2.

Note: m and n will be at most 100.

Ideas:

0 0 0 0
0 1 0 1
1 0 0 0
0 0 0 0

                                                obs [i] [j] matrix

1 1 1 1
1 0 1 2
0 0 1 3
0 0 1 4

                                                dp [i] [j] matrix

If obs [i] [j] == 0, then dp [i] [j] = 0;

如果obs[i][j]!=0,那么dp[i][j]=dp[i-1][j]+dp[i][j-1];(i>1&&j>1)

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

 

Guess you like

Origin blog.csdn.net/weixin_43871369/article/details/92847123