Back In the print window choose "Save as PDF" as the destination
NOTE.CS

Dynamic Programming

1 topic · 28 Nov 2026
1

Dynamic Programming ★★★★★

Algorithm

DP solves a problem by breaking it into overlapping subproblems and storing each answer so it is computed only once. The problem must have optimal substructure.

  • Memoization (top-down) — recursion + cache.
  • Tabulation (bottom-up) — fill a table with loops.

Plain recursion recomputes f(3) and f(2) many times

Plain recursion recomputes f(3) and f(2) many times

0/1 Knapsack O(n × W) · C++
int knapsack(vector<int> &wt, vector<int> &val, int W) {
    int n = wt.size();
    vector<vector<int>> dp(n + 1, vector<int>(W + 1, 0));
    for (int i = 1; i <= n; i++)
        for (int w = 0; w <= W; w++) {
            dp[i][w] = dp[i - 1][w];                                   // skip item
            if (wt[i - 1] <= w)
                dp[i][w] = max(dp[i][w], val[i - 1] + dp[i - 1][w - wt[i - 1]]);  // take item
        }
    return dp[n][W];
}
Longest Common Subsequence · C++
int lcs(string a, string b) {
    int n = a.size(), m = b.size();
    vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
            dp[i][j] = (a[i-1] == b[j-1]) ? dp[i-1][j-1] + 1 : max(dp[i-1][j], dp[i][j-1]);
    return dp[n][m];     // lcs("ABCBDAB", "BDCABA") = 4
}
Coin change · C++
int coinChange(vector<int> &coins, int amount) {      // minimum coins
    vector<int> dp(amount + 1, INT_MAX);
    dp[0] = 0;
    for (int a = 1; a <= amount; a++)
        for (int c : coins)
            if (c <= a && dp[a - c] != INT_MAX)
                dp[a] = min(dp[a], dp[a - c] + 1);
    return dp[amount] == INT_MAX ? -1 : dp[amount];
}