题目如下:
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?
分析如下:
看到这里这段评论写得挺好,就直接贴过来了。This is just Fibonacci numbers. The number of distinct ways for n steps are the sum of distinct ways for n-1 (because we can move 1 step first, then move the rest n - 1 steps) and distinct ways for n - 2 (because we can move 2 steps first, there are two ways to do it: move 1 steps twice and move 2 steps once, the former is a duplicate for the n - 1 case so we should eliminate).
代码如下:
class Solution {
public:
int climbStairs(int n) {
int a1=1;
int a2=2;
int sum=0;
if(n==1)
return 1;
if(n==2)
return 2;
for(int i=3;i<=n;i++){
sum=a1+a2;
a1=a2;
a2=sum;
}
return sum;
}
};
小结:
(1) 本题需要先想想画画,明白题目的本质是斐波那契数列求通项公式的问题。我先一开始用递归,提交发现超时。考虑到递归会比迭代增加更多的时间和空间开销,所以就改为递归,程序就通过了。
2014-10-06 update:
本质和上面一样,只是updae后用数组steps来储存结果,比上面用a1, a2, sum轮流存储的方式易读一些。
class Solution {
public:
int climbStairs(int n) {
int* steps = new int[n + 1];
steps[1] = 1;
steps[2] = 2;
for (int i = 3; i <= n; ++i) {
steps[i] = steps[i - 1] + steps[i - 2];
}
return steps[n];
}
};
和这道题目比较像 。 Leetcode (94) Unique Binary Search Trees