爬楼梯 Climbing-Stairs

题目

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. 1 step + 1 step
2. 2 steps
``````

Example 2:

``````Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
``````

思路&题解

• S(n) = S(n-1)+S(n-2)
• S(2) = 2
• S(1) = 1
• S(0) = 0

``````public int climbStairs(int n) {
if(n==0){
return 0;
} else if(n==1){
return 1;
} else if(n==2){
return 2;
} else {
return climbStairs(n-1)+climbStairs(n-2);
}
}
``````

7 分钟前 通过 0 ms 32.1 MB java
8 分钟前 通过 0 ms 31.7 MB java
21 分钟前 超出时间限制 N/A N/A java

``````int[] cache;
public int climbStairs(int n) {
if (cache==null){
cache = new int[n+1];
}
if(n==0){
return 0;
} else if(n==1){
return 1;
} else if(n==2){
return 2;
} else {
if(cache[n-1]<=0){
cache[n-1] = climbStairs(n-1);
}
if(cache[n-2]<=0){
cache[n-2]=climbStairs(n-2);
}
cache[n]= cache[n-1]+cache[n-2];
return cache[n];
}
}
``````