Fibonacci Number
ID: 509; easy
Solution 1
class Solution {
public int fib(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
int[] dp = new int[n + 1];
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i < n + 1; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
}This the bottom-up tabulation approach. We start from the very "bottom" and add up the numbers until n.
Time complexity: O(n)
Space complexity: O(n)
Solution 2
This is the top-down memoization approach. We use a hash table to achieve memoization.
Time complexity: O(n)
Space complexity: O(n)
Solution 3
This is the bottom-up approach without using an array to keep the results. Instead, we only use three variables to keep the progress.
Time complexity: O(n)
Space complexity: O(1)
Last updated
Was this helpful?