前言
今天是一道很水的水题,爬楼梯。其实就是兔子题👳
题目描述
思路
这道题有很多解法
1.递归
2.dp
3.优化dp O(n) 用临时变量保存前两次状态最后一次上楼梯只能是一阶或者两阶
4.公式求解 O(logn)
代码
1.优化dp
class Solution {
public:
int climbStairs(int n) {
int first = 1;
int second = 2;
int ans = 0;
if(n<=2)
return n;
for(int i=2;i<n;i++)
{
ans = first + second;
first = second;
second = ans;
}
return ans;
}
};
2.公式求解
class Solution {
public:
int climbStairs(int n) {
// 1/sqrt(5)*[((1+sqrt(5))/2) ^(n+1) - ((1-sqrt(5))/2) ^(n+1)]
double sqrt5 = sqrt(5);
return (int) 1/sqrt5*(pow(((1+sqrt5)/2),n+1)-pow((1-sqrt5)/2,n+1));
}
};