Leetcode | Unique Paths I & II

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?

Leetcode | Unique Paths I & II

前面有摘过Unique Path I的解法。n天之后我自己又重写一遍,如下。看来自己的算法能力还是有长进的。

 1 class Solution {

 2 public:

 3     int uniquePaths(int m, int n) {

 4         vector<int> dp(n + 1, 0);

 5         dp[n] = 1;

 6         for (int i = m - 1; i >= 0; --i) {

 7             for (int j = n - 1; j >= 0; --j) {

 8                 dp[j] += dp[j + 1];

 9             }

10             dp[n] = 0;

11         }

12         

13         return dp[0];

14     }

15 };

用一维的dp去优化二维的话,记得每个位置的初始值。这里最边边dp[n]每次都记得还原到0;(第10行)

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.

代码差不多,这个只要有障碍的时候,那个位置设置为0就行了。

 1 class Solution {

 2 public:

 3     int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {

 4         int m = obstacleGrid.size();

 5         if (m <= 0) return 0;

 6         int n = obstacleGrid[0].size();

 7         if (n <= 0) return 0;

 8         

 9         vector<int> dp(n + 1, 0);

10         dp[n] = 1;

11         for (int i = m - 1; i >= 0; --i) {

12             for (int j = n - 1; j >= 0; --j) {

13                 if (obstacleGrid[i][j] == 1) dp[j] = 0;

14                 else dp[j] += dp[j + 1];

15             }

16             dp[n] = 0;

17         }

18         

19         return dp[0];

20     }

21 };

 

 

 

你可能感兴趣的:(LeetCode)