本文实例讲述了java基于斐波那契数列解决兔子问题。分享给大家供大家参考,具体如下:
题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
package com.java.recursion;
/**
* @描述 三种方法实现斐波那契数列
* @项目名称 Java_DataStruct
* @包名 com.java.recursion
* @类名 Fibonacci
* @author chenlin
*/
public class Fibonacci {
/**
* 题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,
* 问每个月的兔子总数为多少?
* month 1 2 3 4 5 6
* borth 0 0 1 1 2 3
* total 1 1 2 3 5 8
*/
/**
* 叠加法
*
* @param month
* @return
*/
public static int getTotalByAdd( int month) {
int last = 1 ; //上个月的兔子的对数
int current = 1 ; //当月的兔子的对数
int total = 1 ;
for ( int i = 3 ; i <= month; i++) {
//总数= 上次+当前
total = last + current;
last= current ;
current = total;
}
return total;
}
/**
* 使用数组
*
* @param month
* @return
*/
public static int getTotalByArray( int month) {
int arr[] = new int [month];
arr[ 1 ] = arr[ 2 ] = 1 ;
for ( int i = 2 ; i < month; i++) {
arr[i] = arr[i - 1 ] + arr[i - 2 ];
}
return arr[month - 1 ] + arr[month - 2 ];
}
public static int getTotalByRecusion( int month) {
if (month == 1 || month == 2 ) {
return 1 ;
} else {
return getTotalByRecusion(month - 1 ) + getTotalByRecusion(month - 2 );
}
}
public static void main(String[] args) {
System.out.println( "快网idc测试结果:" );
System.out.println(getTotalByAdd( 3 ));
System.out.println(getTotalByAdd( 4 ));
System.out.println(getTotalByAdd( 5 ));
System.out.println(getTotalByAdd( 6 ));
}
}
|
运行结果:
希望本文所述对大家java程序设计有所帮助。
原文链接:http://blog.csdn.net/lovoo/article/details/51702689
相关文章
猜你喜欢
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
- 个人网站服务器域名解析设置指南:从购买到绑定全流程 2025-06-10
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-27 89
-
2025-05-29 14
-
2025-05-26 103
-
SparkyLinux 7 “Orion Belt” 评测:稳定性与新鲜感的结合
2025-05-27 39 -
2025-05-27 46
热门评论