import java.util.HashMap;
public class Fib {
static HashMap<Integer, Integer> results = new HashMap<Integer, Integer>();
/**
* F0 =0; <br>
* F1=1 (n=1) <br>
* F2=1 (n=2) <br>
* Fn=Fn-1+Fn-2 (n>=3)
*/
public static int fib(int i) {
int result;
if (i == 0) {
result = 0;
} else if (i == 1) {
result = 1;
} else {
result = fib(i - 1) + fib(i - 2);
}
results.put(i, result);
return result;
}
public static void main(String[] args) {
int cnt = 20;
Fib.fib(cnt);
for (int i = 0; i < cnt; i++) {
System.out.printf("fib(%d) = %d\n", i, results.get(i));
}
}
}
简单实现.
递归是最差的算法.