您的位置:首页 > 产品设计 > UI/UE

Leetcode | Unique Paths I & II

2014-05-10 21:02 561 查看
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?



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

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

return dp[0];
}
};


用一维的dp去优化二维的话,记得每个位置的初始值。这里最边边dp
每次都记得还原到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就行了。

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

return dp[0];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: