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?
思路: 动态规划问题:
最简单的是用m*n大小的数组存储到达每一格的可能情况,然后根据动态规划公式来更新;
改进的地方是,使用O(N)的空间复杂度;一行一行的更新即可.因为每一个元素的值与它数组左边元素相关还和它上面的元素相关.
<span style="font-size:14px;">public class Solution {
public int uniquePaths(int m, int n) {
int[][] paths=new int[m][n];
//最上面一行只有一种到达方式
for(int i=0;i<n;i++)
paths[0][i]=1;
//最左边一行只有一种到达方式
for(int i=1;i<m;i++)
paths[i][0]=1;
//paths[i][j]=paths[i-1][j]+paths[i][j-1];
for(int i=1;i<m;i++){
for(int j=1;j<n;j++){
paths[i][j]=paths[i-1][j]+paths[i][j-1];
}
}
return paths[m-1][n-1];
}
}</span>
改进:
<span style="font-size:14px;"><span style="font-size:14px;">public class Solution {
public int uniquePaths(int m, int n) {
int[] path2=new int[n];
for(int i=0;i<n;i++)
path2[i]=1;
for(int i=1;i<m;i++){
for(int j=1;j<n;j++){
path2[j]+=path2[j-1];
}
}
return path2[n-1];
}
}</span></span>
63.
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
.
代码:
<span style="font-size:14px;">public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m=obstacleGrid.length,n=obstacleGrid[0].length;
int[] path=new int[n];
int i=0;
for(;i<n;i++){
if(obstacleGrid[0][i]==1)
break;
path[i]=1;
}
for(;i<n;i++)
path[i]=0;
for(i=1;i<m;i++){
if(obstacleGrid[i][0]==1)
path[0]=0;
for(int j=1;j<n;j++){
if(obstacleGrid[i][j]==1)
path[j]=0;
else
path[j]+=path[j-1];
}
}
return path[n-1];
}
}</span>
64.
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
<span style="font-size:14px;">public class Solution {
public int minPathSum(int[][] grid) {
int m=grid.length,n=grid[0].length;
int[] cost=new int[n];
cost[0]=grid[0][0];
for(int i=1;i<n;i++){
cost[i]=cost[i-1]+grid[0][i];
}
for(int i=1;i<m;i++){
cost[0]+=grid[i][0];
for(int j=1;j<n;j++){
if(cost[j-1]<cost[j])
cost[j]=cost[j-1]+grid[i][j];
else
cost[j]+=grid[i][j];
}
}
return cost[n-1];
}
}</span>