本文實例講述了java基于斐波那契數(shù)列解決兔子問題。分享給大家供大家參考,具體如下:
題目:古典問題:有一對兔子,從出生后第3個月起每個月都生一對兔子,小兔子長到第三個月后每個月又生一對兔子,假如兔子都不死,問每個月的兔子總數(shù)為多少?
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; /** * @描述 三種方法實現(xiàn)斐波那契數(shù)列 * @項目名稱 Java_DataStruct * @包名 com.java.recursion * @類名 Fibonacci * @author chenlin */ public class Fibonacci { /** * 題目:古典問題:有一對兔子,從出生后第3個月起每個月都生一對兔子,小兔子長到第三個月后每個月又生一對兔子,假如兔子都不死, * 問每個月的兔子總數(shù)為多少? * 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 ; //上個月的兔子的對數(shù) int current = 1 ; //當(dāng)月的兔子的對數(shù) int total = 1 ; for ( int i = 3 ; i <= month; i++) { //總數(shù)= 上次+當(dāng)前 total = last + current; last= current ; current = total; } return total; } /** * 使用數(shù)組 * * @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( "服務(wù)器之家測試結(jié)果:" ); System.out.println(getTotalByAdd( 3 )); System.out.println(getTotalByAdd( 4 )); System.out.println(getTotalByAdd( 5 )); System.out.println(getTotalByAdd( 6 )); } } |
運行結(jié)果:
希望本文所述對大家java程序設(shè)計有所幫助。
原文鏈接:http://blog.csdn.net/lovoo/article/details/51702689