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?
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
.
本文思路:
起初采用的是递归的思想,但是提交后报错说超时,于是采用动态规划的思想,设置了一个同样大小的二维数组,来保存每个位置的路径数。对于Unique Paths II只需将其中的路障位置的路径数设为0即可。
动态规划主要实现依据:table[m][n]=table[m-1][n]+table[m][n-1],其中table就是保存每个位置路径数的二维数组。
代码实现如下:
Unique Paths
public class Solution {
public static int uniquePaths(int m, int n) {
if(m==1||n==1)return 1;
if(m==0||n==0)return 0;
int[][] table=new int[m][n];
table[0][0]=1;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(i==0||j==0)table[i][j]=1;
else table[i][j]=table[i-1][j]+table[i][j-1];
}
}
//int result=getCount(table,m-1,n-1);
return table[m-1][n-1];
}
}
Unique Paths II
public class Solution {
public static int uniquePathsWithObstacles(int[][] obstacleGrid){
int m=obstacleGrid.length;
int n=obstacleGrid[0].length;
if(m==0||n==0)return 0;
int[][] table=new int[m][n];//保存每个位置的路径数
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(obstacleGrid[m-i-1][n-j-1]==1)table[i][j]=0;
else if(i==0&&j==0&&obstacleGrid[m-i-1][n-j-1]==0)table[i][j]=1;
else if(i>0&&j>0){
table[i][j]=table[i-1][j]+table[i][j-1];
}
else if(i>0&&j==0){
table[i][j]=table[i-1][j];
}
else if(i==0&&j>0){
table[i][j]=table[i][j-1];
}
}
}
//int count=getCount(obstacleGrid,m-1,n-1);
return table[m-1][n-1];
}
}