兔子个数问题(斐波那契数列)

古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
程序分析: 兔子的规律为数列1,1,2,3,5,8,13,21....

1.递归解法:

package dataStruct;
import java.util.Scanner;

/**
 * @ClassName: RabbitDG
 * @Description: TODO
 * @Author: hunterm
 * @Date: 2019/8/5 16:00
 * @Version:1.0
 */
public class RabbitDG {
    long sum = 0;
    public static void main(String[] args){
        System.out.println("请输入月数...");
        Scanner sc = new Scanner(System.in);
        long months = sc.nextLong();
        System.out.println("第"+months+"个月,兔子的对数为:"+new RabbitDG().getRabbitSum(months));
    }
    /**
     * 递归方法
     * 1 1 2 3 5 8 13 21
     */
    public long getRabbitSum(long months){
        if(months == 1 || months ==2){
            return 1;
        }else{
            return sum = getRabbitSum(months - 1) + getRabbitSum(months - 2);
        }
    }
}

  2.非递归解法

package dataStruct;

import java.util.Scanner;
/**
 * @ClassName: Rabbit
 * @Description: TODO
 * @Author: hunterm
 * @Date: 2019/8/5 15:46
 * @Version:1.0
 */
public class Rabbit {
    public static void main(String[] args) {
        System.out.println("请输入月数...");
        Scanner sc = new Scanner(System.in);
        long months = sc.nextLong();
        System.out.println("第"+months+"个月,兔子的对数为:"+new Rabbit().get(months));
    }
    /**
     * 规律:1 1 2 3 5 8 13 21
     */
    public long get(long months) {
        long f1 = 1L;
        long f2 = 1L;
        long f = 0;
        if(months == 1 || months == 2){
            return 1;
        }
        for (int i = 3; i <= months; i++) {
            f = f2;
            f2 = f1 + f2;
            f1 = f;
        }
        return f2;
    }
}

  递归方法大家都会,所以面试时一般考察非递归方式求解。

  

posted on 2019-08-05 22:03  时间刺客mht  阅读(1157)  评论(0编辑  收藏  举报

导航