Video in progress
What is dynamic programming? Show the difference between memoization and tabulation on the staircase problem.
DP means splitting a problem into repeating subproblems and solving each one once, then storing the result. Memoization is top-down: recursion plus a cache. Tabulation is bottom-up: filling a table with a loop, starting from the smallest cases.
📖 Answer
The problem: a staircase with n steps, and you climb 1 or 2 steps at a time. How many ways are there? You reach step n either from n-1 or from n-2, so ways(n) = ways(n-1) + ways(n-2).
DP needs two properties to work: the subproblems repeat, and the optimal solution of the big problem is assembled from the solutions of the smaller ones.
Memoization:
static long ways(int n, long[] memo) {
if (n <= 1) return 1;
if (memo[n] != 0) return memo[n];
return memo[n] = ways(n - 1, memo) + ways(n - 2, memo);
}
Tabulation:
static long waysTab(int n) {
long[] dp = new long[n + 2];
dp[0] = 1; dp[1] = 1;
for (int i = 2; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2];
return dp[n];
}
When to use which? Memoization is easier to write, falls straight out of the recursive formula, and computes only the states that are needed. But deep recursion brings a stack risk. Tabulation is faster, uses no stack, and is easy to shrink in memory: here only the last two values are needed, so two variables replace the array.
In an interview, before solving a DP problem, state the meaning of the state out loud: "dp[i] is the number of ways to reach step i". That alone is half the answer.
Sign up to mark studied questions and save your progress.