70.climbStairs

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?

Note: Given n will be a positive integer.

Example 1:

Input: 2

Output: 2

Explanation: There are two ways to climb to the top.

1. 1 step + 1 step

2. 2 steps.

Example 2:

Input: 3

Output: 3

Explanation: There are three ways to climb to the top.

1. 1 step + 1 step + 1 step

2. 1 step + 2 steps

3. 2 steps + 1 step

一个数只能由1和叠加起来,例如5可以由这样叠加起来:


结果可按普通的递归公式得到,但根据规律发现结果与斐波那契数列结果相同,所以使用此方法也可得到结果。

代码1:使用普通方法

int climbStairs(int n) {

    return climb_Stairs(0,n);

}

int climb_Stairs(int i,int n)

{

    if(i>n)

        return 0;

    if(i==n)

        return 1;

    return climb_Stairs(i+1,n)+climb_Stairs(i+2,n);

}

代码2:使用斐波那契数列

int climbStairs1(int n) {

    if(n==1)

        return1;

    int first=1,second=2,third;

    for(int i=3;i<=n;i++)

    {

        third=first+second;

        first=second;

        second=third;

    }

    return second;

}

你可能感兴趣的:(70.climbStairs)