LeetCode之动态规划
62. Unique Paths
Total Accepted: 86710 Total Submissions: 239084 Difficulty: Medium
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?
使用动态规划来求解本题,在每个节点处,只有两个选择,向下或者向右走。本节点可由上一个节点向下或者向右走过来,两种方法:
1)使用一个二位数组count[i][j]来表示从起始点到达坐标(i,j)的,有两种,(i-1,j)-->(i,j)及(i,j-1)-->(i,j),即count[i][j] = count[i-1][j]+count[i][j-1],此时时间复杂度为O(mn),空间复杂度为O(mn)
public class Solution { public int uniquePaths(int m, int n) { int[][] count = new int[m+1][n+1]; for(int i=0;i<=m;i++){ for(int j=0;j<=n;j++){ if(i==0||j==0){ count[i][j] = 0; }else if(i==1&&j==1){ count[i][j]=1; }else{ count[i][j] = count[i-1][j]+count[i][j-1]; } } } return count[m][n]; } }
2)使用一个数组count[i]来表示从起始点到达某一行某一列的路径数量,此时有,count[i] = count[i-1]+count[i],此时,时间复杂度为O(mn),空间复杂度为O(n):
//因为只需求得最终结果,而不需要知道到达每一个坐标的路径数量
public class Solution { public int uniquePaths(int m, int n) { int[] count = new int[n]; count[0]=1; for(int i=0;i<m;i++){ for(int j=1;j<n;j++){ count[i] = count[i-1]+count[i]; } } return count[n-1]; } }
63. 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
.