Dynamic programming can be used when a problem divides into overlapping subproblems that can be solved independently. It is used to find an optimal solution (as large or as small as possible) or to count the solutions. Understanding it is a milestone for every competitive programmer: the idea is simple, the challenge is to apply it to different problems.

Recursive formulation

Coin problem again (chapter 6), now for any coins: form the sum n with as few coins as possible. Let solve(x) be the smallest number of coins for the sum x. For coins {1, 3, 4}: solve(0..10) = 0, 1, 2, 1, 1, 2, 2, 2, 2, 3, 3; for example solve(10) = 3 (3+3+4). Focus on the first coin: it is 1, 3 or 4, and then the rest is a smaller instance of the same problem:

solve(x) = ∞ za x < 0,   solve(0) = 0,   solve(x) = minc solve(x − c) + 1 for x > 0.

Using memoization

Implemented directly, the recursion is exponential, because the same values are computed again and again. Memoization stores each computed value in an array (ready, value), so each solve(x) is computed once. Then the time is O(nk) for the sum n and k coins. Compare the numbers of calls:

#include <bits/stdc++.h>
using namespace std;

const int INF = 1e9;
vector<int> coins = {1, 3, 4};
long long calls = 0;
bool ready[1001];
int value[1001];

// without memoization: exponential
int solveSlow(int x) {
    calls++;
    if (x < 0) return INF;
    if (x == 0) return 0;
    int best = INF;
    for (int c : coins) best = min(best, solveSlow(x - c) + 1);
    return best;
}

// with memoization: each value is computed once
int solve(int x) {
    calls++;
    if (x < 0) return INF;
    if (x == 0) return 0;
    if (ready[x]) return value[x];
    int best = INF;
    for (int c : coins) best = min(best, solve(x - c) + 1);
    value[x] = best;
    ready[x] = true;
    return best;
}

int main() {
    int n;
    cin >> n;
    calls = 0;
    cout << "solveSlow(" << n << ") = " << solveSlow(n) << ", " << calls << " calls" << "\n";
    calls = 0;
    cout << "solve(" << n << ") = " << solve(n) << ", " << calls << " calls" << "\n";
}
30
Output
solveSlow(30) = 8, 4728718 calls
solve(30) = 8, 91 calls

Iterative version and the solution itself

Most competitive programmers fill the array with a loop for x = 0 … n: it is shorter and has smaller constant factors. To print a solution, also remember the first coin of an optimal solution for each sum (first[x]) and follow it from n:

#include <bits/stdc++.h>
using namespace std;

const int INF = 1e9;

int main() {
    int k, n;
    cin >> k;
    vector<int> coins(k);
    for (int &c : coins) cin >> c;
    cin >> n;
    vector<int> value(n + 1), first(n + 1);
    value[0] = 0;
    for (int x = 1; x <= n; x++) {
        value[x] = INF;
        for (int c : coins) {
            if (x - c >= 0 && value[x - c] + 1 < value[x]) {
                value[x] = value[x - c] + 1;
                first[x] = c;  // the first coin of an optimal solution
            }
        }
    }
    cout << value[n] << " coins:";
    for (int x = n; x > 0; x -= first[x]) cout << " " << first[x];
    cout << "\n";
}
3
1 3 4
10
Output
3 coins: 3 3 4

Coins: dynamic programming

Counting the number of solutions

How many ways are there to form the sum x (order matters)? For {1, 3, 4} and x = 5 there are 6: 1+1+1+1+1, 1+1+3, 1+3+1, 3+1+1, 1+4, 4+1. Now solve(x) is the sum of solve(x−c), with solve(0) = 1. The numbers grow fast, so the answer is usually asked modulo m = 109+7:

#include <bits/stdc++.h>
using namespace std;

int main() {
    const long long m = 1000000007;
    int k, n;
    cin >> k;
    vector<int> coins(k);
    for (int &c : coins) cin >> c;
    cin >> n;
    vector<long long> count(n + 1, 0);
    count[0] = 1;
    for (int x = 1; x <= n; x++) {
        for (int c : coins) {
            if (x - c >= 0) {
                count[x] += count[x - c];
                count[x] %= m;
            }
        }
    }
    for (int x = 0; x <= n; x++) cout << "count(" << x << ") = " << count[x] << "\n";
}
3
1 3 4
8
Output
count(0) = 1
count(1) = 1
count(2) = 1
count(3) = 2
count(4) = 4
count(5) = 6
count(6) = 9
count(7) = 15
count(8) = 25

Based on: Antti Laaksonen, Competitive Programmer's Handbook, section 7.1 (CC BY-NC-SA 4.0). Changed: the text is shortened and adapted, the code fragments are complete programs, and the diagrams, tasks and quizzes are new. Adaptation: Boban Blagojević, CC BY-NC-SA 4.0.