62. Unique Paths
题目:从左上到右下,有多少种不同的路径
思路:排列组合
public class Solution {
public int uniquePaths(int m, int n) {
long y = 1, x = 1;
long min = Math.min(m, n);
if(min == 1) return 1;
for(long i = Math.max(m, n); i <= m+n-2; i++){
y *= i;
}
for(long i = 1; i <= min-1; i++){
x *= i;
}
return (int)(y/x);
}
}
动态规划:
public class Solution {
public int uniquePaths(int m, int n) {
int[][] grid = new int[m][n];
for(int i = 0; i<m; i++){
for(int j = 0; j<n; j++){
if(i==0||j==0)
grid[i][j] = 1;
else
grid[i][j] = grid[i][j-1] + grid[i-1][j];
}
}
return grid[m-1][n-1];
}
63. Unique Paths II
题目:有1的位置表示有障碍,统计所有路径数
思路:沿用62题动态规划的方法,遇1路径数为零
public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
int[][] dp = new int[m][n];
dp[0][0] = obstacleGrid[0][0] == 1?0:1;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(i == 0 && j > 0){
if(obstacleGrid[i][j] == 1) dp[i][j] = 0;
else dp[i][j] = dp[i][j-1];
}
if(j == 0 && i > 0){
if(obstacleGrid[i][j] == 1) dp[i][j] = 0;
else dp[i][j] = dp[i-1][j];
}
if(i > 0 && j > 0){
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];
}
}
64. Minimum Path Sum
题目:找到最小路径和
思路:动态规划,很简单
public class Solution {
public int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[][] dp = new int[m][n];
dp[0][0] = grid[0][0];
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(i ==0 && j > 0) dp[i][j] = dp[i][j-1]+grid[i][j];
if(j ==0 && i > 0) dp[i][j] = dp[i-1][j]+grid[i][j];
if(i > 0 && j > 0) dp[i][j] = Math.min(dp[i][j-1], dp[i-1][j]) + grid[i][j];
}
}
return dp[m-1][n-1];
}
}
70. Climbing Stairs
题目:爬梯子,每步1到2级,n步能爬到多少级
思路:斐波那契数列,没啥好说的
public class Solution {
public int climbStairs(int n) {
if(n < 2) return 1;
int pre = 1;
int x = 1;
for(int i = 2; i <= n; i++){
int next = pre+x;
pre = x;
x = next;
}
return x;
}
}