欢迎访问我的剑指offer(第二版)题解目录哦
对应的Leetcode题目可点击leetcode 70. 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
算法设计
假设当有n个台阶时的方案数为 ,那么我们可以发现 , ,当 时,分两种情况:
- 当最后一步只跨了一个台阶时,方案数为
- 当最后一步跨了两个台阶时,方案数为
因此当
时,
这实质上是一个斐波那契数列,只不过这里的第n项是斐波那契数列的第n+1项。
C++代码
递归( )
class Solution {
public:
int climbStairs(int n) { return n == 1 ? 1 : n == 2 ? 2 : climbStairs(n - 1) + climbStairs(n - 2); }
};
循环( )
class Solution {
public:
int climbStairs(int N) {
if (N <= 2)
return N == 1 ? 1 : 2;
int f0 = 1, f1 = 2;
for (int i = 3; i <= N; ++i) {
int f = f0 + f1;
f0 = f1;
f1 = f;
}
return f1;
}
};
通项公式( )
斐波那契数列的通项公式为
class Solution {
public:
int climbStairs(int n) {
double sqrt5 = sqrt(5.0);
return int((pow((1 + sqrt5) / 2.0, n+1) - pow((1 - sqrt5) / 2, n+1)) / sqrt5);
}
};
事实上,由于当n比较大时,
会非常小,我们可以直接舍弃掉这一项,并利用round
函数对
进行四舍五入,再转换回int
类型,也可以得到正确结果,即
class Solution {
public:
int climbStairs(int n) {
double sqrt5 = sqrt(5.0);
return round(pow((1 + sqrt5) / 2.0, n + 1) / sqrt5);
}
};