现在的位置: 首页 > 综合 > 正文

LeetCode Solutions : Unique Paths I & II

2018年12月14日 ⁄ 综合 ⁄ 共 1594字 ⁄ 字号 评论关闭

Unique Paths 

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?

Above is a 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

Solution 1:

public class Solution {
	public int uniquePaths(int m,int n){
		if(m<0||n<0)
			return 0;
		if(m==0||n==0)
			return 1;
		int[][] results=new int[m][n];
		for(int i=0;i<m;i++)
			results[i][0]=1;
		for(int j=0;j<n;j++)
			results[0][j]=1;
		for(int i=1;i<m;i++)
			for(int j=1;j<n;j++)
				results[i][j]=results[i-1][j]+results[i][j-1];
		return results[m-1][n-1];
	}
}

Solution 2:

public class Solution {
    public int uniquePaths1(int m, int n) {
        if(m<0||n<0)
			return 0;
		if(m==0||n==0)
			return 1;
		int[] results=new int[n];
		results[0]=1;
		for(int i=0;i<m;i++)
			for(int j=1;j<n;j++)
				results[j]=results[j]+results[j-1];
		return results[n-1];
    }
}

Unique Paths II 

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 1 and 0 respectively 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.

Solution :

public class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
		int m=obstacleGrid.length;
		int n=obstacleGrid[0].length;
        if(m==0||n==0)
			return 0;
		int[][] results=new int[m][n];
		for(int i=0;i<m;i++){
			for(int j=0;j<n;j++){
				if(obstacleGrid[i][j]==0)
					if(i==0&&j==0)
						results[0][0]=1;
					else
						results[i][j]=(i>0?results[i-1][j]:0)+(j>0?results[i][j-1]:0);
			}
		}
		return results[m-1][n-1];
    }
}


抱歉!评论已关闭.