[LeetCode OJ]-Climbing Stairs

时间:2023-03-10 02:59:08
[LeetCode OJ]-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?

一共有n阶楼梯,每次只能爬1阶或2阶,问爬到顶端一共有多少种方法

方法一:

利用二叉树的思想,对于n=3时有3种方法,有几个叶子节点便有几种方法

[LeetCode OJ]-Climbing Stairs

 void climb( int remainder, int &way)
{
if(remainder== || remainder==)
{
way++;
return;
} climb(remainder-, way);
climb(remainder-, way);
return;
} class Solution {
public:
int climbStairs(int n) {
int result=;
climb(n, result);
return result;
}
};

但是这种方法对于n比较大时会超时,在测试用例中对于n=38就会TLE(Time Limit Exceed)。

方法二:

总结规律,通过以下数据,我们发现

[LeetCode OJ]-Climbing Stairs

way(1)=1

way(n) = way(n-1) + Fibonacci(n-1)    n=2,3,4,5,6,....

 class Solution {
public:
int climbStairs(int n) {
int result=;
int Fibonacci_0=, Fibonacci_1=, temp;
for(int i=; i<n; i++)
{
result += Fibonacci_1;
temp = Fibonacci_1;
Fibonacci_1 = Fibonacci_0 + Fibonacci_1;
Fibonacci_0 = temp; }
return result;
}
};

对于leetcode中所有的测试数据都可以通过