Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallCrashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteTo 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.
| # | Preview | Product | Price | |
|---|---|---|---|---|
| 1 |
|
Dynamic Programming and Optimal Control: Approximate Dynamic Programming | $89.00 | Buy on Amazon |
| 2 |
|
Dynamic Programming and Optimal Control | $89.00 | Buy on Amazon |
| 3 |
|
Dynamic Programming | $45.24 | Buy on Amazon |
| 4 |
|
Dynamic Programming and Optimal Control | $134.50 | Buy on Amazon |
| 5 |
|
Dynamic Programming (Dover Books on Computer Science) | $15.79 | Buy on Amazon |
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.
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 totalingjeither exclude it or include it. The exclude count isT[i - 1][j]; the include count isT[i - 1][j - arr[i - 1]]. Add them. - If its value is greater than
j, it cannot be included, so carry forwardT[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].
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.
Rank #3
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
- Used Book in Good Condition
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.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minuteHow 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.
Best Value
| 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.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.
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
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.




