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:
William Carroll 2020-11-21 14:48:12 +00:00
parent 70e74a4027
commit 417d3b5fff

View 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]