You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
- 1 step + 1 step
- 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
- 1 step + 1 step + 1 step
- 1 step + 2 steps
- 2 steps + 1 step
问有几种方式走到第n级台阶,每次只能走1步或2步
刚开始局限在具体怎么走的思维里,其实不必纠结具体方案,只需要考虑会有几种方式走到。
而且需要倒序地去想,比如现在目标是走到第4级台阶,那假设现在已经到了第4级台阶,应该想我的上一步应该在哪。
因为每次只能走1或2级台阶,所以上一步应该是在第2级或第3级台阶。
那么就是两种方式走到第4级的:
- 起点 -> 第2级 -> (2步)第4级
- 起点 -> 第3级 -> (1步)第4级
所以走到第4级台阶有(走到第2级台阶的方式数 + 走到第3级台阶方式数)种方式。
现在问题转化成有几种方式走到第2级和第3级,同理倒序地去想。
因此可以用动态规划来解决,建立动态规划数组dp[n] (n为目标的台阶数)
根据上面的思路和例子,n=4时,第4级台阶需要考虑第2级和第3级的方式数,所以dp[n]=dp[n-1] + dp[n-2],这样一步一步往回推
而已知dp[1] = 1, 到达第一级台阶只有一种方式
dp[2] = 2, 到达第2级台阶有两种方式(2个1步或者一个2步)
因此可以推导出n级台阶的方式
而由于dp[n] = dp[n-1] + dp[n-2] 和Fibonacci数列的公式一样,所以这道题可转换为求Fibonacci数列,而且可以根据Fibonacci数列的一些性质直接计算,可以降低复杂度
*注意点:公式由n=2开始计算的,所以开始要考虑到n=1的情况
动态规划方法代码
public int climbStairs(int n) {
if(n <= 1) {
return 1;
}
int[] dp = new int[n];
dp[0] = 1;
dp[1] = 2;
for(int i = 2; i < n; i++) {
dp[i] = dp[i-1] + dp[i-2];
}
return dp[n-1];
}
这道题有个类似的二维推广,就是63题,unique path2
A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).
Now consider if some obstacles are added to the grids. How many unique paths would there be?
Input:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
Output: 2
Explanation:
There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
- Right -> Right -> Down -> Down
- Down -> Down -> Right -> Right
从左上角走到右下角有多少条路径的问题
思路也是倒序思维
有障碍物时dp[i][j] = 0, 没有时就是dp[i][j] = dp[i][j-1] + dp[i-1][j]
当i=0或者j=0时
int row = obstacleGrid.length;
int col = obstacleGrid[0].length;
int[][] dp = new int[row][col];
if(obstacleGrid[0][0] == 1) {
dp[0][0] = 0;
} else {
dp[0][0] = 1;
}
for(int i = 1; i < col; i++) {
if(obstacleGrid[0][i] == 1) {
dp[0][i] = 0;
} else {
dp[0][i] = dp[0][i-1];
}
}
for(int i = 1; i < row; i++) {
if(obstacleGrid[i][0] == 1) {
dp[i][0] = 0;
} else {
dp[i][0] = dp[i-1][0];
}
}
for(int i = 1; i < row; i++) {
for(int j = 1; j < col; j++) {
if(obstacleGrid[i][j] == 1) {
dp[i][j] = 0;
} else {
dp[i][j] = dp[i][j-1] + dp[i-1][j];
}
}
}
return dp[row-1][col-1];