跳台阶问题

来源:互联网 发布:国际地图导航软件 编辑:程序博客网 时间:2024/06/07 00:40

跳台阶

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

思路:对于第n个台阶来说,只能从n-1或者n-2的台阶跳上来,所以F(n) = F(n-1) + F(n-2),即斐波拉契数序列1、2、3、5……。

/** * @author lanxuewei * 方法1->迭代 * 方法2->递归 * */public class Solution {    //方法1->迭代    public int JumpFloor1(int target) {        int first = 1;        int second = 2;        int temp = 0;        if(target <= 2){            return target;        } else{            for(int i = 3; i <= target; i++){                temp = first + second;                first = second;                second = temp;            }        }        return second;    }    //方法2->递归    public int JumpFloor2(int target) {        if (target <= 0) {            return 0;        } else if (target == 1) {            return 1;        } else if (target ==2) {            return 2;        } else {            return JumpFloor2(target-1) + JumpFloor2(target-2);        }    }    public static void main(String[] args) {        //测试        Solution test = new Solution();        System.out.println("result1 = " + test.JumpFloor1(5));        System.out.println("result2 = " + test.JumpFloor2(5));    }}

不过以本人愚见,这题使用迭代即可,使用递归反而多增加开销罢了。

变态跳台阶

问题描述:一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
直接贴代码:

package test;public class Solution {    /**     * n级台阶,第一步有n种跳法:跳1级、跳2...跳n级     * 跳1级,剩下n-1级,则剩下跳法是f(n-1)     * 跳2级,剩下n-2级,则剩下跳法是f(n-2)     * ...     * 易得f(n)=f(n-1)+f(n-2)+...+f(1)     * 当n = n-1时,有f(n-1)=f(n-2)+f(n-3)+...+f(1)     * 由上两式得 f(n)=2*f(n-1)     * @param target     * @return result     */    public int JumpFloorII(int target) {        if (target <= 0){            return -1;        } else if (target == 1){            return 1;        } else{            return 2 * JumpFloorII(target-1);        }    }    public static void main(String[] args){        //测试        Solution test = new Solution();        int result = test.JumpFloorII(5);        System.out.println("result = " + result);    }}

首先得到公式:f(n)=2*f(n-1),然后直接使用递归即可。