剑指offer——青蛙跳

问题

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

方法一:递归


public class Solution1 {
    /**
     * 运行时间:489ms
     * 占用内存:9308k
     * @param target
     * @return
     */
    public int JumpFloor(int target) {
        if (target == 1)
            return 1;
        else if (target ==2)
            return 2;
        else if (target>2){
            return JumpFloor(target-1)+JumpFloor(target-2);
        }
        return 0;
    }

}

方法二:while遍历

public class Solution2 {
    /**
     * 运行时间:19ms
     * 占用内存:9348k
     * @param target
     * @return
     */
    public int JumpFloor(int target) {
        if (target == 1)
            return 1;
        else if (target ==2)
            return 2;
        else if (target>2){
            int max1 = 1;
            int max2 = 2;
            int count =2;
            while (count<target){
                int temp = max2;
                max2 = max2+max1;
                max1 = temp;
                count++;
            }
            return max2;
        }
        return 0;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章