C Algorithms: Dynamic Programming, Backtracking & N-Queens Masterclass
Welcome to Phase 19 (Chapter 54): C Algorithms โ Dynamic Programming, Backtracking & N-Queens Masterclass! Dynamic Programming (DP) and Backtracking solve hard combinatorial optimization problems. In this guide, you will master top-down memoization, bottom-up tabulation, 0/1 Knapsack DP, and N-Queens state-space backtracking.
DP applies when a problem has Overlapping Subproblems and Optimal Substructure.
| Approach | Strategy | Implementation | Space Overhead |
|---|---|---|---|
| Memoization | Top-Down | Recursive + Cache Array | Call Stack + Cache Array |
| Tabulation | Bottom-Up | Iterative Loop + DP Table | DP Table Array only |
#include <stdio.h>
#include <stdlib.h>
static int max(int a, int b) { return (a > b) ? a : b; }
int knapsackDP(int W, int wt[], int val[], int n) {
int K[n + 1][W + 1];
for (int i = 0; i <= n; i++) {
for (int w = 0; w <= W; w++) {
if (i == 0 || w == 0)
K[i][w] = 0;
else if (wt[i - 1] <= w)
K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]);
else
K[i][w] = K[i - 1][w];
}
}
return K[n][W];
}
int main(void) {
int val[] = {60, 100, 120};
int wt[] = {10, 20, 30};
int W = 50;
printf("Optimal 0/1 Knapsack Value: %d\n", knapsackDP(W, wt, val, 3));
return 0;
} Q1: Why does 0/1 Knapsack require DP while Fractional Knapsack uses Greedy?
In 0/1 Knapsack, items cannot be broken. Taking an item may waste capacity, requiring evaluation of all sub-capacities using DP.
Q2: What is the time complexity of 0/1 Knapsack DP?
O(N ยท W), where N is number of items and W is knapsack capacity (pseudo-polynomial time).
Q3: How does backtracking prune invalid state search trees?
Backtracking checks safety constraints before exploring sub-branches. If a branch violates rules (e.g. Queen under attack), it abandons the branch immediately.
Q4: How do you optimize 0/1 Knapsack space to O(W)?
Since DP row `i` only depends on row `i-1`, you can use a single 1D array traversed backward from `W` to `0`.
Q5: What is the Longest Common Subsequence (LCS) DP problem?
LCS finds the longest sequence of characters appearing in the same order in two strings in O(M ยท N) time.