優化的斐波那契數列
阿新 • • 發佈:2018-12-01
private Map<Integer, Long> memo = new HashMap<>(); // 遞迴演算法:簡單地用了一下快取思想 private long fab(int n) { if (memo.get(n) != null) { return memo.get(n); } if (n == 1 || n == 2) { memo.put(n, 1L); return 1; } else { long temp = fab(n-1) + fab(n-2); memo.put(n, temp); return temp; } }
// bottom to up 演算法 private static int fab(int n) { int[] store = new int[n+1]; for (int i = 1; i <= n; i++) { if (i == 1 || i == 2) { store[i] = 1; } else { store[i] = store[i-1] + store[i-2]; } } return store[n]; }