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).ideHow many possible unique paths are there?spa
state: dp[x][y]表示從起點到x,y的路徑數 function: 每一步的路徑至關於從它左邊一步和它上邊一步的加和 dp[x][y] = dp[x - 1][y] + dp[x][y - 1] intialize: dp[0][0] = 1 // dp[0][i] = 1, dp[i][0] = 1// 二維數組裏面第一行和第一列都爲1 由於從起始點到此點的方法只有一種 answer: dp[n-1][m-1]
時間是O(mn) 空間O(mn)code
public int uniquePaths(int m, int n) { int[][] dp = new int[m][n]; dp[0][0] = 1; for (int i = 1; i < n; i++) { dp[0][i] = dp[0][i - 1]; } for (int i = 1; i < m; i++) { dp[i][0] = dp[i - 1][0]; } 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]; }
咱們能夠用一個一維數組, 每次下一行的數來覆蓋上一行以節省空間it
時間 O(m*n) 空間 O(n)io
public int uniquePaths(int m, int n) { int[] dp = new int[n]; dp[0] = 1; for (int i = 0; i < m; i++) { for (int j = 1; j < n; j++) { dp[j] += dp[j - 1]; } } return dp[n - 1]; }
Follow up for "Unique Paths":function
Now consider if some obstacles are added to the grids. How many unique
paths would there be?gridAn 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.im[ [0,0,0], [0,1,0], [0,0,0] ] The total number of unique paths
is 2.
與1相同, 可是若是此處爲1的話那麼路徑數應當爲0
時間是O(mn) 空間O(mn)
public int uniquePathsWithObstacles(int[][] obstacleGrid) { int m = obstacleGrid.length; int n = obstacleGrid[0].length; int[][] dp = new int[m][n]; for (int i = 0; i < m; i++) { if (obstacleGrid[i][0] != 1) { dp[i][0] = 1; } else { break;//後面全部的都沒法到達因此break } } for (int j = 0; j < n; j++) { if (obstacleGrid[0][j] != 1) { dp[0][j] = 1; } else { break; } } for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { if (obstacleGrid[i][j] == 1) { dp[i][j] = 0; } else { dp[i][j] = dp[i-1][j] + dp[i][j - 1]; } } } return dp[m - 1][n - 1]; }
時間 O(m*n) 空間O(n)
public int uniquePathsWithObstacles(int[][] obstacleGrid) { int m = obstacleGrid.length; int n = obstacleGrid[0].length; int[] dp = new int[n]; dp[0] = 1; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (obstacleGrid[i][j] == 1) { dp[j] = 0; } else { if (j > 0) { dp[j] += dp[j - 1]; } } } } return dp[n - 1]; }