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

[Lintcode] Unique Paths I,II

2016-04-25 22:19 381 查看
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
;
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];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lintcode