[Lintcode] Unique Paths I,II
来源:互联网 发布:csgo淘宝买激活码 编辑:程序博客网 时间:2024/05/21 21:38
Unique Paths I
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?
一维滚动数组实现。
public class Solution { /** * @param n, m: positive integer (1 <= n ,m <= 100) * @return an integer */ public int uniquePaths(int m, int n) { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = 1; for(int i = 1; i < m; i++) { for(int j = 1; j < n; j++) { res[j] += res[j - 1]; } } return res[n - 1]; }}
Unique Paths II
加入墙,此时考虑两种情况,墙在最左侧时,墙在中间时。
在最左侧时,要初始化一维数组的首元素为0。在最上恻时,不用考虑,因为迭代时是从左向右迭代,当遇到1时,保留i-1的路径数量即可。但是在左侧时,每次重新开始时都会魔人存在一条路径。
public class Solution { /** * @param obstacleGrid: A list of lists of integers * @return: An integer */ public int uniquePathsWithObstacles(int[][] obstacleGrid) { int height = obstacleGrid.length; if(height == 0) return 0; int width = obstacleGrid[0].length; int[] res = new int[width]; if(height == 1 && width == 1 && obstacleGrid[0][0] == 0) return 1; for(int i = 0; i < width; i++) { if(obstacleGrid[0][i] != 1){ res[i] = 1; } else { break; } } for(int i = 1; i < height; i++) { if(obstacleGrid[i][0] == 1) res[0] = 0; for(int j = 1; j < width; j++) { if(obstacleGrid[i-1][j] != 1 && obstacleGrid[i][j-1] != 1) res[j] += res[j - 1]; else if(obstacleGrid[i-1][j] == 1 && obstacleGrid[i][j-1] == 1) res[j] = 0; else if(obstacleGrid[i-1][j] == 1) res[j] = res[j-1]; else if(obstacleGrid[i][j-1] == 1) res[j] = res[j]; } } return obstacleGrid[height - 1][width - 1] == 1 ? 0 : res[width - 1]; }}
0 0
- [Lintcode] Unique Paths I,II
- lintcode: Unique Paths II
- Unique Paths I & II
- Unique Paths I,II
- Unique Paths I II
- Unique Paths I,II
- [LeetCode]Unique Paths I & II
- 【LeetCode】Unique Paths I && II
- Unique Paths I | II leetcode
- LeetCode | Unique Paths I,II
- LeetCode Solutions : Unique Paths I & II
- Unique Paths I,II, Minimum Path Sum
- leetcode-62&63 Unique Paths I & II
- Leetcode(62)(63) Unique Paths I II
- 62 & 63. Unique Paths I & II
- [Leetcode] #62#63 Unique Paths I & II
- lintcode unique-paths-ii 不同的路径ii
- Unique Paths & Unique Paths II
- EditText限制不能输入空格,汉字和字符不超过28
- 【BZOJ 4517】排列计数 - 排列组合+乘法逆元
- zoj--3946--Highway Project(SPFA)
- H.264(MPEG-4 AVC)级别(Level)、DPB 与 MaxDpbMbs 详解
- python编码问题
- [Lintcode] Unique Paths I,II
- 算法与数据结构(JAVA)-排序算法总结
- 【C++】输出格式
- [POJ1655]Balancing Act(树形dp)
- java 栈与队列
- hadoop完全分布式集群安装
- iOS动画解析
- android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an appli
- Golang tls 链接通信