题目描述

一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

解题思路

1,用递归,将问题转换为f(n)=f(n-1)+f(n-2);
2,用迭代,原理类似

代码实现

/** * */
package 递归和循环;

/** * <p> * Title:JumpFloor * </p> * <p> * Description: * </p> * * @author 田茂林 * @data 2017年8月23日 上午11:31:34 */
public class JumpFloor {
    public int IntJumpFloor(int target) {
        if(target==1){
            return 1;
        }
        if(target==2){
            return 2;
        }
        int num =0;
        if(target>2){
            num = IntJumpFloor(target-1)+IntJumpFloor(target-2);
        }
        return num;

    }
    //==============================================迭代版本
    public int IntJumpFloorSuper(int target) {
        if(target==1){
            return 1;
        }
        if(target==2){
            return 2;
        }
        int before =2;
        int beforeagain =1;
        int end =0;
        for (int i = 3; i <=target; i++) {
            end  = before+beforeagain;
            beforeagain = before;
            before = end;
        }
        return end;

    }
}