GuilinDev

Lc0509

05 August 2008

509 Fibonacci Number

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
    // 把记录计算结果的散列表作为类变量 // 以防每次递归调用时被改变或者手动传递麻烦   
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();

    int fibo(int number) {
        if (number < 2) {
            return number;
        } else {
            if (!map.containsKey(number)) {//防止重复运算子问题             
                map.put(number, fibo(number - 1) + fibo(number - 2));
            }
        }
        return map.get(number);
    }
}
1
2
3
4
5
6
7
8
9
10
11
class Solution {
    int fibo(int number) {
        int[] arr = new int[number + 1];
        arr[0] = 0;
        arr[1] = 1;
        for (int i = 2; i < number + 1; i++) {
            arr[i] = arr[i - 1] + arr[i - 2];
        }
        return arr[number];
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
    int fibo(int number) {
        if (number < 2) {
            return number;
        } else {
            int num1 = 0;
            int num2 = 1;
            int result = 0;
            for (int i = 2; i < number + 1; i++) {
                result = num1 + num2;
                num1 = num2;
                num2 = result;
            }
            return result;
        }
    }
}