Fibonacci DP

The simplest DP family: each answer depends on a fixed handful of earlier answers, so a loop and two or three variables solve it in O(n) time and O(1) space.

Overview

The shape of the recurrence

The Fibonacci numbers start 0, 1 and each next number is the sum of the two before it: F(n) = F(n−1) + F(n−2). Many problems have the same shape. The answer at position i depends only on the answers at a few positions just before it, and nothing else. That shape is what this topic calls Fibonacci DP.

Each member of the family says what dp[i] means and how to build it from the cells just before it.

  • Fibonacci: dp[i] is the i-th number, and it is the sum dp[i-1] + dp[i-2].
  • Climbing Stairs: dp[i] is the number of ways to reach step i. It is the same sum, dp[i-1] + dp[i-2].
  • Tribonacci: dp[i] is the i-th number, and it sums three cells, dp[i-1] + dp[i-2] + dp[i-3].
  • Min Cost Climbing Stairs: dp[i] is the cheapest way to stand on step i. It takes the min of dp[i-1] + cost[i-1] and dp[i-2] + cost[i-2].
  • House Robber: dp[i] is the most money from houses 0 to i. It takes the max of dp[i-1] and dp[i-2] + value[i].
  • Decode Ways: dp[i] is the number of ways to decode the first i digits. It is dp[i-1] if the last digit is valid, plus dp[i-2] if the last pair is valid, so a sum with conditions.

The combine step changes (sum, min or max) but the plan never does: base cases, then a loop from left to right. Before writing that loop, it helps to see why the obvious recursive code is not good enough.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio