https://leetcode.com/problems/unique-paths/description/
https://leetcode.com/problems/unique-paths-ii/description/
代码:
class Solution {
public int uniquePaths(int m, int n) {
int[][] dp = new int[m][n];
for (int i = 0; i < m; i++) {
dp[i][0] = 1;
}
for (int j = 0; j < n; j++) {
dp[0][j] = 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];
}
}
follow-up:
class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int rowNum = obstacleGrid.length;
int colNum = obstacleGrid[0].length;
int[][] dp = new int[rowNum][colNum];
dp[0][0] = obstacleGrid[0][0] == 0 ? 1 : 0;
for (int i = 1; i < rowNum; i++) {
dp[i][0] = (obstacleGrid[i][0] == 0 && dp[i - 1][0] > 0) ? 1 : 0;
}
for (int j = 1; j < colNum; j++) {
dp[0][j] = (obstacleGrid[0][j] == 0 && dp[0][j - 1] > 0) ? 1 : 0;
}
for (int i = 1; i < rowNum; i++) {
for (int j = 1; j < colNum; j++) {
dp[i][j] = (obstacleGrid[i][j] == 1) ? 0 : (dp[i - 1][j] + dp[i][j - 1]);
}
}
return dp[rowNum - 1][colNum - 1];
}
}