剑指:跳台阶

一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。

分析:

因为只能跳1级或2,假设n阶有f(n)种跳法。

所以有两种情况:

a、如果第一次跳的是1阶,那么剩下的n-1个台阶,跳法有f(n-1)。

b、如果第一次跳的是2阶,那么剩下的n-2个台阶,跳法有f(n-2)。

所以,可以得出总跳法:f(n) = f(n-1) + f(n-2)

而实际我们知道:只有一阶的时候 f(1) = 1;只有二阶的时候 f(2) = 2;即相当于是个斐波那契数列。

解:

我们可以递归的方式:

public class Solution {
    public int JumpFloor(int target) {
        if(target <= 0)
            return -1;
        if(target == 1)
            return 1;
        if(target == 2)
            return 2;
        else
            return JumpFloor(target-1) + JumpFloor(target-2);
    }
}

递归的方式开销可能会很大,因为递归里面有很多重复的计算,所以我们可以改成迭代的方式。

public class Solution {
    public int JumpFloor(int target) {
        if(target <= 0)
            return -1;
        if(target == 1)
            return 1;
        if(target == 2)
            return 2;
        int n1 = 1;
        int n2 = 2;
        int total = 0;
        for(int i=2; i<target; i++){
            total = n1 + n2;
            n1 = n2;
            n2 = total;
        }
        return total;
    }
}