509. Fibonacci Number
Last updated
Last updated
/**
* Time complexity : O(2^N), The amount of operations needed, for each level
* of recursion, grows exponentially as the depth approaches N.
* Space complexity : O(N), We need space proportionate to N to account for
* the max size of the stack, in memory.
*/
public class Solution {
public int fib(int N) {
if (N <= 1) {
return N;
}
return fib(N-1) + fib(N-2);
}
}/**
* Time complexity : O(N)
* Space complexity : O(1)
*/
class Solution {
public int fib(int n) {
if(n < 2) {
return n;
}
int prev = 0;
int curr = 1;
for(int i = 2; i <= n; i++) {
int temp = prev + curr;
prev = curr;
curr = temp;
}
return curr;
}
}