编程语言:JAVA
题目描述:
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
提交反馈:
45 / 45 test cases passed.
Status: Accepted
Runtime: 2 ms
Submitted: 0 minutes ago
You are here!
Your runtime beats 100.00 % of java submissions
解题思路:
递归法,n级台阶共S(n)中方法,S(n)=S(n-1)+S(n-2),
这个递归公式的理解为,当爬到n-1级台阶时候,到n级只有一种方法,即一步跨上去;
当爬到n-2级台阶的时候,直接到n级只有一种方法,两补一次跨上去(一步+一步这种方法会到达n-1级台阶,与S(n-1)重复)。
当然这种递归方法时间复杂度比较高,很容易超时。
最后参考别人的博客用动态规划填表的思路做完这道题,时间复杂度O(n),
设置了三个变量,空间复杂度也很低。可以说是很好的解决方案了。
提交后显示:Submission Result: Time Limit Exceeded
递归法代码:
class Solution {
public int climbStairs(int n) {
if(n == 1){
return 1;
}
if(n == 2){
return 2;
}
return climbStairs(n-1) + climbStairs(n-2);
}
}
提交后显示:Submission Result: Time Limit Exceeded
动态规划填表法代码
class Solution {
public int climbStairs(int n) {
if(n==1){
return 1;
}
if(n==2){
return 2;
}
int i = 3;
int n_1 = 1;
int n_2 = 2;
while(i < n){
int tmp = n_1;
n_1 = n_2;
n_2 = tmp+n_2;
i += 1;
}
return n_1 + n_2;
}
}
本文探讨了经典的爬楼梯问题,给出了两种JAVA实现方案:递归法和动态规划填表法,并对比了它们的时间复杂度及优缺点。

被折叠的 条评论
为什么被折叠?



