What is dynamic programming?
Answer
Dynamic programming (DP) is an optimization technique for problems with overlapping subproblems and optimal substructure. It solves each subproblem once and stores the result (memoization or tabulation), avoiding redundant recomputation. Two approaches: (1) Top-down (Memoization): recursion + caching. Solve the problem recursively, but store computed results in a hash map or array. First call computes; subsequent calls return cached result. More intuitive, may have stack overhead; (2) Bottom-up (Tabulation): iterative, fill a table from base cases upward. No recursion overhead, typically more space-efficient. Steps to solve DP: (1) Identify if DP applies (overlapping subproblems, optimal substructure); (2) Define state clearly (what does dp[i] represent?); (3) Write the recurrence relation (dp[i] in terms of previous states); (4) Identify base cases; (5) Determine computation order. Classic problems: Fibonacci, 0/1 Knapsack, Longest Common Subsequence, Longest Increasing Subsequence, Coin Change, Edit Distance, Matrix Chain Multiplication, Rod Cutting. DP transforms exponential brute force into polynomial time.