假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。
示例 1:
输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。
1. 1 阶 + 1 阶
2. 2 阶
示例 2:
输入: 3
输出: 3
解释: 有三种方法可以爬到楼顶。
1. 1 阶 + 1 阶 + 1 阶
2. 1 阶 + 2 阶
3. 2 阶 + 1 阶
解法:
直接使用递归
#include <iostream>
using namespace std;
class Solution {
private:
void selectStair(int remainStep, int& count)
{
if(remainStep == 0)//当剩余步数为0,说明找到一种方法,计数加一
{
count++;
return;
}
if(remainStep >= 2)//当剩余台阶大于等于2时,有选择余地
{
selectStair(remainStep-1, count);//走一阶
selectStair(remainStep-2, count);//走两阶
}
else if(remainStep == 1)
{
selectStair(remainStep - 1, count);//当剩余台阶等于1,没有选择余地,只能走一阶
}
}
public:
//使用递归,超出时间限制
int climbStairs(int n)
{
int count = 0, remainStep = n;//count记录多少种方法,remainStep剩余多少台阶
selectStair(remainStep, count);
return count;
}
};
int main()
{
Solution s;
cout << s.climbStairs(44) << endl;
return 0;
}
解法2:
斐波那契数列
n F(n)
1 -> 1
2 -> 2
3 -> 3
4 -> 5
5 -> 8
6 -> 13
7 -> 21
8 -> 34
9 -> 55
10 -> 89
#include <iostream>
using namespace std;
class Solution
{
private:
int F(int n)
{
if(n == 1)
return 1;
if(n == 2)
return 2;
if(n > 2)
return F(n - 1) + F(n - 2);
}
public:
int climbStairs(int n)
{
return F(n);
}
};
int main()
{
Solution s;
cout << s.climbStairs(10) << endl;
return 0;
}
QT Creator编译通过但是leetcode上不行
解法3:
实际是根据解法2推到过来的F(n) = F(n - 1) + F(n - 2)
数组实现斐波那契数列,走n阶梯查找对应下标所对应的值
#include <iostream>
using namespace std;
class Solution
{
public:
int climbStairs(int n)
{
int* dp = new int[n + 1];
dp[0] = 1;
dp[1] = 1;
for(int i=2; i<=n; i++)
{
dp[i] = dp[i-1] + dp[i-2];
}
return dp[n];
}
};
int main()
{
Solution s;
cout << s.climbStairs(44) << endl;
return 0;
}