优化的斐波那契数列

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/M_sdn/article/details/84202888
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];
    }

猜你喜欢

转载自blog.csdn.net/M_sdn/article/details/84202888