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]; }