斐波那契:递归算法

Recursion.java

http://www.gwdang.com

http://www.gwdang.com/app/extension

 

 

view sourceprint   ?  

01 import java.io.BufferedReader;
02 import java.io.IOException;
03 import java.io.InputStreamReader;
04 import java.util.HashMap;
05 import java.util.Iterator;
06 import java.util.Map;
07 import java.util.Set;
08  
09 /**
10  * 递归求斐波那契数列
11  * 个人理解
12  * @author Administrator
13  *
14  */
15 public class Recursion {
16  
17     /**
18      * @param args

n

19      */
20     public static void main(String[] args) {
21         // TODO Auto-generated method stub
22         BufferedReader strin=new BufferedReader(new InputStreamReader(System.in));
23         int n=0;
24         try {
25             System.out.println("请输入50以内数字:");
26             n=Integer.parseInt(strin.readLine());
27         } catch (NumberFormatException e) {
28             // TODO Auto-generated catch block
29             e.printStackTrace();
30         } catch (IOException e) {
31             // TODO Auto-generated catch block
32             e.printStackTrace();
33         }
34         System.out.println(Fibonacci.fibonacci(n));
35         Fibonacci.printMap();
36     }
37  
38 }
39 /**
40  * 工具类
41  * 添加了缓存控制
42  * 重点
43  * @author Administrator
44  *
45  */
46 class Fibonacci{
47     private static Map m=new HashMap();//用于保存n对应的斐波那契值
48       static long fibonacci(int n){
49        if(n<=1) return 1;
50        //缓存!如果存在直接返回
51        if(m.containsKey(n))
52            return (long)m.get(n);
53        long store=fibonacci(n-1)+fibonacci(n-2);
54        m.put(n, store);
55        return store;
56        }
57       /**
58        * 对m的读取可能破坏了封装
59        * 打印出map
60        */
61       public static void printMap(){
62           Set keySet = m.keySet();
63           Iterator keys=keySet.iterator();
64             while(keys.hasNext()){
65                 int temp=(int)keys.next();
66                 System.out.println(temp+":"+m.get(temp));
67             }
68            
69       }
70 }

你可能感兴趣的:(斐波那契:递归算法)