Implement a bottom-up fibonacci
The bottom-up solution run in O(n) time instead of O(2^n) time, which the
recursive solution runs as:
```
def fib(n):
return fib(n - 2) + fib(n - 1)
```
Remember that exponential algorithms are usually recursive algorithms with
multiple sibling calls to itself.
This commit is contained in:
parent
70e74a4027
commit
417d3b5fff
1 changed files with 6 additions and 0 deletions
6
scratch/facebook/interview-cake/nth-fibonacci.py
Normal file
6
scratch/facebook/interview-cake/nth-fibonacci.py
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
def fib(n):
|
||||||
|
cache = (0, 1)
|
||||||
|
for _ in range(n):
|
||||||
|
a, b = cache
|
||||||
|
cache = (b, a + b)
|
||||||
|
return cache[0]
|
||||||
Loading…
Add table
Add a link
Reference in a new issue