October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

Count Subsets That Reach a Target: The Dynamic Programming Method

Count subsets that reach an exact target with include/exclude dynamic programming, including the zero-value edge case and working Python code.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To count subsets whose elements sum to an exact target, keep a count for each array prefix and each sum. For every element, add the ways that exclude it to the ways that include it. The key initialization is one way to make zero using the empty subset; this also lets zero-valued elements correctly double the count.

What the problem asks

Given an array and a target sum, count the subsets whose elements add up to exactly that target. Each array position can be chosen at most once, so this is a 0/1 choice: include an element or exclude it. If equal values appear at different positions, choosing one position rather than the other represents a distinct subset.

As an Amazon Associate I earn from qualifying purchases.

For example, with [2, 3, 5] and target 5, the valid subsets are [5] and [2, 3]. The answer is 2.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Define the dynamic-programming state

Let T[i][j] be the number of subsets of the first i array elements that sum exactly to j. With n elements and target target, the desired result is T[n][target].

For the next element, arr[i - 1], there are two cases:

  • If its value is at most j, subsets totaling j either exclude it or include it. The exclude count is T[i - 1][j]; the include count is T[i - 1][j - arr[i - 1]]. Add them.
  • If its value is greater than j, it cannot be included, so carry forward T[i - 1][j].

In recurrence form, for nonnegative array values and sums:

T[i][j] = T[i - 1][j] + T[i - 1][j - arr[i - 1]] when arr[i - 1] ≤ j; otherwise T[i][j] = T[i - 1][j].

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Initialize the table, including the zero-sum case

Set T[0][0] = 1: with no elements, the empty subset is one way to make sum zero. Set T[0][j] = 0 for every positive j, since no elements cannot make a positive sum. All other cells are filled by the recurrence.

Do not automatically set every T[i][0] to one. If the prefix contains zeros, each zero can either be included or left out without changing the sum. For example, [0] has two subsets totaling zero—the empty subset and the subset containing the zero. With [0, 0], there are four. The usual recurrence handles this: for a zero, the include and exclude terms refer to the same previous sum and are added. In the tabulation below, sums therefore start at zero.

Fill the table bottom-up

A two-dimensional table makes the prefix-based recurrence explicit. This implementation assumes nonnegative integer array values and a nonnegative integer target.

Rank #4
def count_subsets(arr, target):
    n = len(arr)
    dp = [[0] * (target + 1) for _ in range(n + 1)]
    dp[0][0] = 1

    for i in range(1, n + 1):
        value = arr[i - 1]
        for total in range(target + 1):
            dp[i][total] = dp[i - 1][total]
            if value <= total:
                dp[i][total] += dp[i - 1][total - value]

    return dp[n][target]

The table uses (n + 1) × (target + 1) entries, so this version takes O(n × target) time and O(n × target) space. Those bounds describe this tabulation approach; they depend on the numeric target because the table has a column for each sum.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How counting differs from existence and optimization

The include/exclude structure appears in several familiar problems, but the stored result and combine operation change with the question.

Problem What each state stores How include and exclude are combined
0/1 knapsack Best value Take the maximum
Subset-sum feasibility Whether a sum is possible Logical OR
Count of subsets Number of ways Add the counts

Counting is not interchangeable with checking whether a subset exists: a feasible-sum state can be true even when there are many different subsets that achieve it. For counting, preserve and add the number of ways from both choices.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Memoize the same recurrence

A top-down solution can cache each pair of index and remaining sum. Use a marker distinct from any valid answer: zero is a legitimate count, so it cannot also mean “not computed.”

def count_subsets_memo(arr, target):
    n = len(arr)
    memo = [[None] * (target + 1) for _ in range(n + 1)]

    def count(i, remaining):
        if i == 0:
            return 1 if remaining == 0 else 0
        if memo[i][remaining] is not None:
            return memo[i][remaining]

        value = arr[i - 1]
        ways = count(i - 1, remaining)
        if value <= remaining:
            ways += count(i - 1, remaining - value)

        memo[i][remaining] = ways
        return ways

    return count(n, target)

This version uses the same nonnegative-value assumption, and it avoids exploring the same state repeatedly by storing its result. Its recursion depth can grow with the number of elements.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Common mistakes to avoid

  • Using OR instead of addition: OR answers whether a sum is reachable, not how many subsets reach it.
  • Forgetting the empty subset: without T[0][0] = 1, valid include/exclude counts cannot build correctly.
  • Hard-coding one way to make zero: zeros create distinct include/exclude choices, so the count for zero can grow.
  • Treating zero as an uncached memo value: store an explicit uncomputed marker such as None.

For the standard table indexed from zero through the target, values and target must be nonnegative integers. Negative values require a different state range because a sum could move below zero.

For the source’s instructional framing and examples, see Nishant Gaurav’s explanation on DEV Community.

Quick Recap

Bestseller No. 3
Bestseller No. 4
Dynamic Programming and Optimal Control
Dynamic Programming and Optimal Control
Used Book in Good Condition
$134.50

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.