Subset sum

Decide whether any subset of an array sums to a given target. The general table-building behind many knapsack-style problems.

Time O(n × target)Space O(n × target)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

dp[i, t] asks whether sum t is reachable using only the first i numbers. It is reachable either by ignoring number i (dp[i-1, t]) or, if it fits, by using number i and reaching the remaining amount with the earlier numbers (dp[i-1, t - a[i-1]]).

Code

public static bool SubsetSum(int[] a, int target) {
    var dp = new bool[a.Length + 1, target + 1];
    for (int i = 0; i <= a.Length; i++) dp[i, 0] = true;
    for (int i = 1; i <= a.Length; i++)
        for (int t = 1; t <= target; t++)
            dp[i, t] = dp[i - 1, t] || (a[i - 1] <= t && dp[i - 1, t - a[i - 1]]);
    return dp[a.Length, target];
}
static boolean subsetSum(int[] a, int target) {
    boolean[][] dp = new boolean[a.length + 1][target + 1];
    for (int i = 0; i <= a.length; i++) dp[i][0] = true;
    for (int i = 1; i <= a.length; i++)
        for (int t = 1; t <= target; t++)
            dp[i][t] = dp[i - 1][t] || (a[i - 1] <= t && dp[i - 1][t - a[i - 1]]);
    return dp[a.length][target];
}
bool subsetSum(const vector<int>& a, int target) {
    int n = a.size();
    vector<vector<bool>> dp(n + 1, vector<bool>(target + 1, false));
    for (int i = 0; i <= n; i++) dp[i][0] = true;
    for (int i = 1; i <= n; i++)
        for (int t = 1; t <= target; t++)
            dp[i][t] = dp[i - 1][t] || (a[i - 1] <= t && dp[i - 1][t - a[i - 1]]);
    return dp[n][target];
}
def subset_sum(a: list[int], target: int) -> bool:
    dp = [[False] * (target + 1) for _ in range(len(a) + 1)]
    for i in range(len(a) + 1): dp[i][0] = True
    for i in range(1, len(a) + 1):
        for t in range(1, target + 1):
            dp[i][t] = dp[i - 1][t] or (a[i - 1] <= t and dp[i - 1][t - a[i - 1]])
    return dp[len(a)][target]

Tips

In the .NET library

This is the same table shape as 0/1 knapsack and partition equal subset sum, just asking a yes/no question about one explicit target instead of maximising value or forcing an exact half.