Published on

# Fibonacci with dynamic programming

Authors

## Problem

The Fibonacci numbers, commonly denoted `F(n)` form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from `0` and `1`. That is,

`_2F(0) = 0, F(1) = 1_2F(n) = F(n - 1) + F(n - 2), for n > 1.`

Given `n`, calculate `F(n)`.

Example 1:

`_3Input: n = 2_3Output: 1_3Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.`

Example 2:

`_3Input: n = 3_3Output: 2_3Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.`

Example 3:

`_3Input: n = 4_3Output: 3_3Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.`

Constraints:

• `0 <= n <= 30`

## Solution

### Recursion

• Find a base recursive call, in this case is condition where input equals with 0 will return 0 and 1 will return 1
• Then from the description above, call the recursive with F(n-1) + F(n-2)
`_8_8func fibonacci(n int) int{_8 if n==0 || n==1{_8 return n_8 }_8_8 return fibonacci(n-1)+fibonacci(n-2)_8}`

### Dynamic programming

• First step similar with recursive, early return if n equals 0 or 1
• Use memoize to compose calculation
`_14func fib(n int) int {_14 if n==0 || n==1{_14 return n_14 }_14_14 dp:=make([]int, n+1)_14 dp[0]=0_14 dp[1]=1_14 for i:=2;i<n+1;i++{_14 dp[i] = dp[i-2]+dp[i-1]_14 }_14_14 return dp[n]_14}`

But let's remove unnecessary array

`_15func fib(n int) int {_15 if n==0 || n==1{_15 return n_15 }_15_15 a, b, ans:= 0, 1, 0_15_15 for i:= 1; i < n; i++{_15 ans = a + b;_15 a = b;_15 b = ans;_15 }_15_15 return ans;_15}`