leetcode 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?

Subscribe to see which companies asked this question

刚开始用递归做的,递归比较麻烦的在于没有用空间存储吧,所以时间比较慢。

其实思路不能再简单了,就是斐波那契数列,改了一下而已就是F(1)=1,F(2)=2,F(n)=F(n-1)+F(n-2)

和那天当当网的那个也很像,发现这种题目其实画二叉树的话比较容易找到思路。

class Solution {
public:
    int climbStairs(int n) {
    int array[n];
    array[0]=1;
    array[1]=2;
    for(int i=2;i<n;i++){
        array[i]=array[i-1]+array[i-2];
    }
    return array[n-1];    
    }
};
原文地址:https://www.cnblogs.com/LUO77/p/4977780.html