代码改变世界

8.跳台阶

2018-12-30 18:06  YihangZhou  阅读(96)  评论(0编辑  收藏  举报

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

 

思路:

对于本题,前提只有 一次 1阶或者2阶的跳法。

a.如果两种跳法,1阶或者2阶,那么假定第一次跳的是一阶,那么剩下的是n-1个台阶,跳法是f(n-1);

b.假定第一次跳的是2阶,那么剩下的是n-2个台阶,跳法是f(n-2)

c.由a\b假设可以得出总跳法为: f(n) = f(n-1) + f(n-2) 

d.然后通过实际的情况可以得出:只有一阶的时候 f(1) = 1 ,只有两阶的时候可以有 f(2) = 2

e.可以发现最终得出的是一个斐波那契数列:

        

              | 1, (n=1)

f(n) =     | 2, (n=2)

              | f(n-1)+f(n-2) ,(n>2,n为整数)

 

public class Solution {    
    public int JumpFloor(int target) {
        int a=1;
        int b=2;
        int c=target;
        for(int i=3;i<=target;i++){
            c=a+b;
            a=b;
            b=c;
        }
        return c;
    }   
}

 

 

 

回溯

public class Solution {
    private int count;
    public int JumpFloor(int target) {
        count=0;
        int i=0;
        reJumpFloor(target,0);
        return count;
    }
    public void reJumpFloor(int target,int i){
        if(i>=target){
            if(i==target) {
                count++;
            }
        }else{
            for(int k=1;k<=2;k++){
                reJumpFloor(target,i+k);
            }
        }
    }
}