原题链接:https://leetcode.com/problems/climbing-stairs/
同斐波那契数列:
class Solution {
public:
int climbStairs(int n) {
int s1 = 1,s2 = 2,s3;
if(n == s1) return s1;
if(n == s2) return s2;
for(int i = 3;i <= n;i++)
{
s3 = s2 + s1;
s1 = s2;
s2 = s3;
}
return s3;
}
};
递归解法:
#include <iostream>
using namespace std;
void climbWays(int n,int &cnt,int curSteps)
{
if(curSteps > n)
return;
if(curSteps == n)
{
cnt++;
return;
}
climbWays(n,cnt,curSteps+1);
climbWays(n,cnt,curSteps+2);
}
int climbStairs(int n) {
int cnt = 0;
int curSteps = 0;
climbWays(n,cnt,curSteps);
return cnt;
}
int main(int argc, char *argv[])
{
cout << climbStairs(10) << endl;
cout << climbStairs(15) << endl;
cout << climbStairs(20) << endl;
cout << climbStairs(25) << endl;
cout << climbStairs(30) << endl;
return 0;
}