首页 > 代码库 > Climbing Stairs

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?

解题思路:

这是一个典型的斐波那契数列,对于有n步的台阶:

1、如果先跳1步,还剩余n-1步,那么这就变成n-1步台阶跳法数目;

2、如果先跳2步,还剩余n-2步,这就变成n-2步台阶跳法数目。

所以经典的表达式:f(n) = f(n-1) + f(n-2)

class Solution {
public:
    int climbStairs(int n) {
        /*f(n)=f(n-1)+f(n-2)*/
        if(n==0||n==1) return  1;
        int stepOne=1,stepTwo=1;
        int result=0;
        for(int i=2;i<=n;i++){
            result=stepOne+stepTwo;
            stepTwo=stepOne;
            stepOne=result;
        }
        return result;
    }
};