70. Climbing Stairs

来源:互联网 发布:mac版ae插件安装路径 编辑:程序博客网 时间:2024/06/16 14:22

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个台阶可以先上n-2个,最后上2个。//f(n)=f(n-1)+f(n-2)//但是不能直接递归,递归会超时。class Solution {public:    int climbStairs(int n) {        int a=1,b=2;                if(n==1)return a;        if(n==2)return b;                int res=0;        for(int i=2;i<n;i++){            res=a+b;            a=b;            b=res;        }        return res;    }};


0 0