Dynamic programming (DP) applies when a problem has optimal substructure (the answer is built from answers to smaller problems) and overlapping subproblems (the same small problems recur). Solve each subproblem once and store the result. Two styles exist: memoization (top-down) and tabulation (bottom-up). Steps: define the state, write the recurrence, set base cases, choose the fill order.
Remember
state : ways[i] = ways to reach step i
recurrence: ways[i] = ways[i - 1] + ways[i - 2]
base : ways[0] = 1, ways[1] = 1
Reference
Cheat Sheet
Keep these facts handy while you work with Dynamic Programming Basics in C in C.
Topic
Detail
State
What a table cell means
Recurrence
How cells depend on smaller ones
Base cases
Smallest answers
Style
Memoization or tabulation
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Memoization in C.
Example 1 — Ways to climb stairs
Take one or two steps at a time up five steps.
C
#include <stdio.h>
int main(void) {
int n = 5;
int ways[6];
ways[0] = 1;
ways[1] = 1;
for (int i = 2; i <= n; i++) ways[i] = ways[i - 1] + ways[i - 2];
printf("ways[0..5]:");
for (int i = 0; i <= n; i++) printf(" %d", ways[i]);
printf("\nways to climb %d steps: %d\n", n, ways[n]);
return 0;
}
Output
ways[0..5]: 1 1 2 3 5 8
ways to climb 5 steps: 8
How It Works
The last move was either a 1-step from i-1 or a 2-step from i-2, so the counts add.
Each table entry is computed once from two earlier entries.
Without the table, the recursion would recompute the same values exponentially often.
Edge Cases & Pitfalls
Check these before relying on Dynamic Programming Basics in C in real programs.
state
Vague state definition
If you cannot say exactly what a cell means, the recurrence will be wrong.
order
Wrong fill order
A cell must be computed after all the cells it depends on.
Remember
Key Takeaways
Optimal substructure plus overlap.
State, recurrence, base, order.
Store answers.
One line: Dynamic programming (DP) applies when a problem has optimal substructure (the answer is built from answers to smaller problems) and overlapping subproblems (the same small problems recur).
Frequently Asked Questions
A technique that solves complex problems by breaking them into overlapping subproblems and storing each result to avoid recomputation.
Divide and conquer splits into independent subproblems; DP handles overlapping subproblems by caching them.
Continue with "Memoization in C" next. Cache recursive results so each subproblem is computed once. The C Algorithm Techniques hub lists every topic in order.