LintCode -- 不同的路径 II
2015-09-29 18:20
281 查看
LintCode -- unique-paths-ii(不同的路径 II)
原题链接:http://www.lintcode.com/zh-cn/problem/unique-paths-ii/
跟进“不同的路径”:
现在考虑网格中有障碍物,那样将会有多少条不同的路径?
网格中的障碍和空位置分别用1和0来表示。
样例
如下所示在3x3的网格中有一个障碍物:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
一共有2条不同的路径从左上角到右下角。
注意
m和n均不超过100
分析:
dp[ i ][ j ] = dp [ i+1 ][ j ] + dp[ i ][ j+1 ]
**** 时间复杂度 O(n*m), 空间复杂度 O(n*m) ****
代码(C++、Java、Python):
原题链接:http://www.lintcode.com/zh-cn/problem/unique-paths-ii/
跟进“不同的路径”:
现在考虑网格中有障碍物,那样将会有多少条不同的路径?
网格中的障碍和空位置分别用1和0来表示。
样例
如下所示在3x3的网格中有一个障碍物:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
一共有2条不同的路径从左上角到右下角。
注意
m和n均不超过100
分析:
dp[ i ][ j ] = dp [ i+1 ][ j ] + dp[ i ][ j+1 ]
**** 时间复杂度 O(n*m), 空间复杂度 O(n*m) ****
代码(C++、Java、Python):
class Solution { public: /** * @param obstacleGrid: A list of lists of integers * @return: An integer */ int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) { // write your code here int m = obstacleGrid.size(); int n = obstacleGrid[0].size(); vector<vector<int>> dp; dp.resize(m+1); for (int i = 0; i < m+1; i++){ dp[i].resize(n+1); dp[i] = 0; } for (int i = 0; i < n+1; i++) dp[m][i] = 0; for (int i = m-1; i >= 0; i--) for (int j = n-1; j >= 0; j--){ if (obstacleGrid[i][j] == 1) dp[i][j] = 0; else if (i == m-1 && j == n-1) dp[i][j] = 1; else dp[i][j] = dp[i+1][j] + dp[i][j+1]; } return dp[0][0]; } };
public class Solution { /** * @param obstacleGrid: A list of lists of integers * @return: An integer */ public int uniquePathsWithObstacles(int[][] obstacleGrid) { // write your code here int m = obstacleGrid.length; int n = obstacleGrid[0].length; int [][] dp = new int [m+1][n+1]; for (int i = m-1; i >= 0; i--) for (int j = n-1; j >= 0; j--){ if (obstacleGrid[i][j] == 1) dp[i][j] = 0; else if (i == m-1 && j == n-1) dp[i][j] = 1; else dp[i][j] = dp[i+1][j] + dp[i][j+1]; } return dp[0][0]; } }
class Solution: """ @param obstacleGrid: An list of lists of integers @return: An integer """ def uniquePathsWithObstacles(self, obstacleGrid): # write your code here m = len(obstacleGrid) n = len(obstacleGrid[0]) dp = [[0 for i in range(n+1)] for j in range(m+1)] for i in list(reversed(range(m))): for j in list(reversed(range(n))): if obstacleGrid[i][j] == 1: dp[i][j] = 0 elif i == m-1 and j == n-1: dp[i][j] = 1 else: dp[i][j] = dp[i+1][j] + dp[i][j+1] return dp[0][0]
相关文章推荐
- C++进阶学习——单例模式的实现
- jsp与servlet的联系
- 用jquery面向对象实现的简单的图片轮播,还能学习一下闭包哦
- java mongodb 修改
- iOS9适配 之 关于info.plist 第三方登录 添加URL Schemes白名单
- scala学习笔记一
- State Threads 回调终结者
- EJB中的拦截器
- Centos6/7来网络引导(pxe)安装centos
- General Problem Solving Techniques [Beginner-1]~H - Songs
- DriverStudio工具包介绍
- Python DeprecationWarning 类型错误
- Spring annotation 之lookup (方法注入)
- 如何删除微软拼音输入法2007
- 解决img标签间距问题
- textview属性
- MFC消息机制逆向追踪
- Netcat简介
- 在fragment中添加上下文菜单
- 用jquery动画实现的简单的图片轮播