[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
原创粉丝点击