62.不同路径
java
class Solution {
public int uniquePaths(int m, int n) {
//1dp数组 m n代表位置,dp[m][n]代表到达这里的途径个数
int [][] dp = new int[m][n];
//3初始化
for(int i = 0;i<n;i++){
dp[0][i] = 1;
}
for(int j = 0;j<m;j++){
dp[j][0] = 1;
}
//4遍历顺序
for(int i = 1;i<m;i++){
for(int j = 1;j<n;j++){
//2递推公式
dp[i][j] = dp[i-1][j]+dp[i][j-1];
}
}
return dp[m-1][n-1];
}
}
63. 不同路径 II
java
class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
int [][] dp = new int [m][n];
//如果在起点或终点出现了障碍,直接返回0
if (obstacleGrid[m - 1][n - 1] == 1 || obstacleGrid[0][0] == 1) {
return 0;
}
for(int i = 0;i<n;i++){
if(obstacleGrid[0][i]==1){
break;
}
dp[0][i]=1;
}
for(int j=0;j<m;j++){
if(obstacleGrid[j][0]==1) break;
dp[j][0] = 1;
}
for(int i = 1;i<m;i++){
for(int j = 1;j<n;j++){
if(obstacleGrid[i][j]==0){
dp[i][j] = dp[i-1][j] +dp[i][j-1];
}
}
}
return dp[m-1][n-1];
}
}