Fibonacci Number
ID: 509; easy
Last updated
class Solution {
private Map<Integer, Integer> map = new HashMap<>();
public int fib(int n) {
if (n <= 1) return n;
map.putIfAbsent(0, 0);
map.putIfAbsent(1, 1);
if (map.containsKey(n)) {
return map.get(n);
}
map.put(n, fib(n - 1) + fib(n - 2));
return map.get(n);
}class Solution {
public int fib(int n) {
if (n <= 1) return n;
int x = 0, y = 1, z = 1;
for (int i = 3; i < n + 1; i++) {
x = y;
y = z;
z = x + y;
}
return z;
}
}
// x y z
// x y z
// 0 1 1 2 3 5 8