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.
3. 1 step + 1 step + 1 step
4. 1 step + 2 steps
5. 2 steps + 1 step
這是一個爬樓梯問題,自己18年在面試小米公司的時候遇到過,當時聽完面試官說這道題的時候自己一臉懵逼,面試官後來講完解題思路自己纔有點恍然大悟,昨天在回京的火車上又看到這道題,今天記錄一下。
這個問題實際上跟斐波那契數列非常相似,假設梯子有n層,那麼如何爬到第n層呢,因爲每次只能爬1或2步,那麼爬到第n層的方法要麼是從第 n-1 層一步上來的,要不就是從 n-2 層2步上來的,所以遞推公式非常容易的就得出了:dp[n] = dp[n-1] + dp[n-2]。
Java 解法一:
public static int climbStairs(int n) {
if (n == 1) {
return 1;
}
int dynamicArray[] = new int[n + 1];
dynamicArray[1] = 1;
dynamicArray[2] = 2;
for (int i = 3; i <= n; i++) {
dynamicArray[i] = dynamicArray[i - 1] + dynamicArray[i - 2];
}
return dynamicArray[n];
}
我們可以對空間進行進一步優化,只用兩個整型變量a和b來存儲過程值,首先將 a+b 的值賦給b,然後a賦值爲原來的b,所以應該賦值爲 b-a 即可。這樣就模擬了上面累加的過程,而不用存儲所有的值,參見代碼如下:
Java解法2:
public class Solution {
public int climbStairs(int n) {
int a = 1, b = 1;
while (n-- > 0) {
b += a;
a = b - a;
}
return a;
}
}
或者
public static int climbStairs4(int n) {
int a = 1, b = 1;
while (--n > 0) {
b += a;
a = b - a;
}
return b;
}
當然還有使用數組做緩存的方法
Java解法3
public class ClimbingStairs {
public static int climbStairsWithRecursionMemory(int n) {
int[] memoryArray = new int[n + 1];
return subClimbStairsWithRecursionMemory(n - 1, memoryArray) + subClimbStairsWithRecursionMemory(n - 2, memoryArray);
}
public static int subClimbStairsWithRecursionMemory(int n, int[] memoryArray) {
if (n == 1) {
return 1;
} else if (n == 2) {
return 2;
} else {
if (memoryArray[n] > 0) {
return memoryArray[n];
}
memoryArray[n] = subClimbStairsWithRecursionMemory(n - 1, memoryArray) + subClimbStairsWithRecursionMemory(n - 2, memoryArray);
return memoryArray[n];
}
}
}
另外還有其他方法
參考文章 算法:Climbing Stairs(爬樓梯) 6種解法
70. Climbing Stairs 爬樓梯問題
https://leetcode.com/problems/climbing-stairs/solution/