leetcode 63:Unique Paths II
2015-11-19 20:56
309 查看
题目:
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
in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
The total number of unique paths is
Note: m and n will be at most 100.
思路:
这题和Unique Paths很像,只不过加了一个路障,我们可以把路障地方的DP设置为0.则可以将Unique
Paths的动态规划方法用过来。
时间复杂度:O(m*n)
实现如下:
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& nums) {
int size1 = nums.size();
if (size1 < 1) return 0;
int size2 = nums[0].size();
vector<vector<int>> DP(size1, vector<int>(size2, 1));
for (int i = 0; i < size1; i++)
for (int j = 0; j < size2; j++)
{
if (nums[i][j] == 1) DP[i][j] = 0; //注意这一步处理
else if (i > 0 && j > 0) DP[i][j] = DP[i][j - 1] + DP[i - 1][j];
else if (i > 0) DP[i][j] = DP[i-1][j];
else if(j>0) DP[i][j] = DP[i][j - 1];
}
return DP[size1 - 1][size2 - 1];
}
};
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
1and
0respectively
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.
思路:
这题和Unique Paths很像,只不过加了一个路障,我们可以把路障地方的DP设置为0.则可以将Unique
Paths的动态规划方法用过来。
时间复杂度:O(m*n)
实现如下:
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& nums) {
int size1 = nums.size();
if (size1 < 1) return 0;
int size2 = nums[0].size();
vector<vector<int>> DP(size1, vector<int>(size2, 1));
for (int i = 0; i < size1; i++)
for (int j = 0; j < size2; j++)
{
if (nums[i][j] == 1) DP[i][j] = 0; //注意这一步处理
else if (i > 0 && j > 0) DP[i][j] = DP[i][j - 1] + DP[i - 1][j];
else if (i > 0) DP[i][j] = DP[i-1][j];
else if(j>0) DP[i][j] = DP[i][j - 1];
}
return DP[size1 - 1][size2 - 1];
}
};
相关文章推荐
- Android进阶-复杂的UI框架(一)
- maven项目出现web.xml is missing and <failOnMissingWebXml> is set to true错误的解决办法
- leetcode 62:Unique Paths
- Android进阶-如何避免频繁修改UI代码
- UI基础_UITableView
- Android进阶-子线程中刷新UI的讨论
- UIView与AVLayer
- ### Error building SqlSession.
- 芒果iOS开发UI课程第三节UITextField
- UI - UIDatePicker
- 教你如何开发VR游戏系列教程四:UI 设计
- CharSequence的getText()与String的getString()区别和为什么加""
- 响应者链和 UILabel的userInteractionEnabled属性
- 《iOS Human Interface Guidelines》——Design Principles
- 利用 UIAppearance 协议自定义控件外观
- UI学习之常用方法(续)
- UITableViewCell自定义高度
- 自定义UINavigationController的后退按钮标题
- Fuel-OpenStack架构学习
- IOS UINavigationBar 导航栏 全局样式设置