Java练习:青蛙跳台阶

一只青蛙一次可以跳上1级台阶,也可以跳上2级。

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

1级,1种跳法

2级,2种跳法

 

求当n=10,20,50,100时有多少种跳法。

 

要点1:需要使用BigInteger表达特别大的整数;

要点2:当n=100时,不能简单地使用递归。

 

import java.math.BigInteger;

public class Main {

    public static void main(String[] args) {
        Frog.init(1000);
        int[] ar = {10, 20, 50, 100};
        for (int i : ar) {
            System.out.println(Frog.jumpSteps(i));
        }
    }
}

class Frog {
    static BigInteger[] array;

    public static void init(int maxSteps) {
        array = new BigInteger[maxSteps];
        array[1] = new BigInteger("1");
        array[2] = new BigInteger("2");
    }

    public static BigInteger jumpSteps(int steps) {
        if (array[steps]== null){
            BigInteger option1 = jumpSteps(steps - 1);
            BigInteger option2 = jumpSteps(steps - 2);
            array[steps] = option1.add(option2);
        }
        return array[steps];
    }
}

 

运行结果:

89
10946
20365011074
573147844013817084101

 

或者直接使用递推计算:

import java.math.BigInteger;

public class Main {

    public static void main(String[] args) {
        int[] ar = {10, 20, 50, 100};
        for (int i : ar) {
            System.out.println(Frog.jumpSteps(i));
        }
    }
}

class Frog {

    public static BigInteger jumpSteps(int steps) {
        BigInteger[] array = new BigInteger[steps + 1];
        array[1] = new BigInteger("1");
        array[2] = new BigInteger("2");
        for (int i=3; i<= steps; i++) {
            array[i] = array[i-1].add(array[i-2]);
        }
        return array[steps];
    }
}

 

posted @ 2021-02-27 20:20  我的成功之路  阅读(101)  评论(0)    收藏  举报