目录
62 不同路径
63 不同路径 ||
62 不同路径
class Solution {public int uniquePaths(int m, int n) {int f[][] = new int[m][n];for(int i = 0;i < m;i++)f[i][0] = 1;for(int i = 0;i < n;i++)f[0][i] = 1;for(int i = 1;i < m;i++){for(int j = 1;j < n;j++){f[i][j] += f[i - 1][j];f[i][j] += f[i][j - 1];}}return f[m - 1][n - 1];}
}
时间复杂度O(n×m)
空间复杂度O(n×m)
63 不同路径 ||
class Solution {public int uniquePathsWithObstacles(int[][] obstacleGrid) {int n = obstacleGrid.length;int m = obstacleGrid[0].length;if(obstacleGrid[0][0] == 1 || obstacleGrid[n - 1][m - 1] == 1)return 0;int f[][] = new int[n][m];f[0][0] = 1;for(int i = 1;i < n;i++)if(obstacleGrid[i][0] == 0 && i > 0 && f[i - 1][0] == 1)f[i][0] = 1;for(int i = 1;i < m;i++)if(obstacleGrid[0][i] == 0 && i > 0 && f[0][i - 1] == 1)f[0][i] = 1;for(int i = 1;i < n;i++){for(int j = 1;j < m;j++){if(obstacleGrid[i][j] == 0){f[i][j] += f[i - 1][j] + f[i][j - 1];}}}return f[n - 1][m - 1];}
}
时间复杂度O(n×m)
空间复杂度O(n×m)