62.不同路径
1 确定dp数组
dp[i][j代表到达该格子的路径数量
2 确定递推公式
机器人每次只能向下或者向右移动一步, dp[i][j]= dp[i - 1][j]+ dp[i][j - 1]
3 dp数组如何初始化
dp[i][0]一定都是1,因为从(0, 0)的位置到(i, 0)的路径只有一条,同理,dp[0][j]也都是1
4 确定遍历顺序
从[1][1]开始从左到右,从上一层到下一层遍历
5 举例推导dp数组 。。。
class Solution {public int uniquePaths(int m, int n) {int[][] dp = new int[m][n];for(int row = 0; row < m; row++){dp[row][0] = 1;}for(int col = 0; col < n; col++){dp[0][col] = 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];}
}
63. 不同路径 II
和62类似,只是需要处理障碍的情况,保持障碍处dp[i][j] = 0;
class Solution {public int uniquePathsWithObstacles(int[][] obstacleGrid) {int m = obstacleGrid.length;int n = obstacleGrid[0].length;int[][] dp = new int[m][n];if (obstacleGrid[m - 1][n - 1] == 1 || obstacleGrid[0][0] == 1) {return 0;}for(int row = 0; row < m && obstacleGrid[row][0] == 0; row++){dp[row][0] = 1;}for(int col = 0; col < n && obstacleGrid[0][col] == 0; col++){dp[0][col] = 1;}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];}
}