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).ide
How many possible unique paths are there?
優化
時間 O(NM) 空間 O(NM)spa
由於要走最短路徑,每一步只能向右方或者下方走。因此通過每個格子路徑數只可能源自左方或上方,這就獲得了動態規劃的遞推式,咱們用一個二維數組dp儲存每一個格子的路徑數,則dp[i][j]=dp[i-1][j]+dp[i][j-1]
。最左邊和最上邊的路徑數都固定爲1,表明一直沿着最邊緣走的路徑。code
public class Solution { public int uniquePaths(int m, int n) { int[][] dp = new int[m][n]; for(int i = 0; i < m; i++){ dp[i][0] = 1; } for(int i = 0; i < n; i++){ dp[0][i] = 1; } for(int i = 1; i < m; i++){ for(int j = 1; j < n; j++){ dp[i][j] = dp[i-1][j] + dp[i][j-1]; } } return dp[m-1][n-1]; } }
時間 O(NM) 空間 O(N)it
實際上咱們能夠複用每一行的數組來節省空間,每一個元素更新前的值都是其在二維數組中對應列的上一行的值。這裏dp[i] = dp[i - 1] + dp[i]
;io
public class Solution { public int uniquePaths(int m, int n) { int[] dp = new int[n]; for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ // 每一行的第一個數都是1 dp[j] = j == 0 ? 1 : dp[j - 1] + dp[j]; } } return dp[n - 1]; } }
Follow up for "Unique Paths":class
Now consider if some obstacles are added to the grids. How many unique paths would there be?grid
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.
時間 O(NM) 空間 O(NM)
解法和上題如出一轍,只是要判斷下當前格子是否是障礙,若是是障礙則通過的路徑數爲0。須要注意的是,最上面一行和最左邊一列,一旦遇到障礙就再也不賦1了,由於沿着邊走的那條路徑被封死了。
public class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { int m = obstacleGrid.length, n = obstacleGrid[0].length; int[][] dp = new int[m][n]; for(int i = 0; i < m; i++){ if(obstacleGrid[i][0] == 1) break; dp[i][0] = 1; } for(int i = 0; i < n; i++){ if(obstacleGrid[0][i] == 1) break; dp[0][i] = 1; } for(int i = 1; i < m; i++){ for(int j = 1; j < n; j++){ dp[i][j] = obstacleGrid[i][j] != 1 ? dp[i-1][j] + dp[i][j-1] : 0; } } return dp[m-1][n-1]; } }
時間 O(NM) 空間 O(N)
和I中的空間優化方法同樣,不過這裏判斷是不是障礙物,並且每行第一個點的值取決於上一行第一個點的值。
public class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { int[] dp = new int[obstacleGrid[0].length]; for(int i = 0; i < obstacleGrid.length; i++){ for(int j = 0; j < obstacleGrid[0].length; j++){ dp[j] = obstacleGrid[i][j] == 1 ? 0 : (j == 0 ? (i == 0 ? 1 : dp[j]) : dp[j - 1] + dp[j]); } } return dp[obstacleGrid[0].length - 1]; } }