Target Sum
Count the ways to put plus or minus signs on numbers to reach a total
DSA, Medium, 2-D DP
Which structure or algorithm, and what does it cost.
A list nums holds whole numbers. Write a plus or a minus sign in front of every number, then add them all up. Count the sign choices whose sum is exactly target. Equal numbers are different numbers, so giving them different signs counts as a different choice.
Examples
Constraints
- 1 <= length of
nums<= 40. - 0 <= each number <= 30.
- -2,000 <=
target<= 2,000.
Your answer must contain
- The simple method and why it is too slow; the better method; the best method and why it is correct; code; time and memory cost; a hand trace of example 1.
Target Aim for O(n * total) time and O(total) memory, where total is the sum of the numbers.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
Each number gets a plus or a minus. Track the running sum as you go. How many different running sums can exist after each number?
Hint 2 the approach
Many sign choices reach the same running sum, so you can count them together instead of one by one. What would you store for each number and sum?
Hint 3 the key step
Keep a map from each running sum to the number of sign choices that reach it. Can the plus group be seen as a subset with one fixed sum?
Walkthrough
Full walkthrough brute force to best
Brute force
Give each number a sign: 2^n choices, and check each sum. For 40 numbers that is about 10^12 choices, too slow.
Better method
Recursion with memory. Let ways(i, sum_so_far) be the number of sign choices for the numbers from position i onward that end on the target. Store each pair. The running sum lies between -total and total, so there are n * (2 * total + 1) pairs: O(n * total) time and memory.
Best method
Turn the problem into a subset sum count. Let P be the sum of the numbers with a plus and T the total of all numbers. The numbers with a minus add up to T - P, so the final sum is P - (T - P) = 2 * P - T, which gives P = (T + target) / 2. If |target| is larger than T, or T + target is odd, no choice works and the answer is 0. Otherwise count the subsets of the numbers whose sum is exactly P. Keep a list ways, where ways[s] is the number of subsets with sum s, starting with ways[0] = 1. For each number x, go through the sums from P down to x and add ways[s - x] to ways[s]. Going downward means one number is never used twice. A zero doubles every entry, which is right, because it can take either sign.
Hand trace
Run on nums = [2, 4, 1, 3, 6], target = 4. The total is 16, so want = (16 + 4) / 2 = 10. The list ways[0] to ways[10] starts as [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]. After number 2: [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]. After number 4: [1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0]. After number 1: [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0]. After number 3: [1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1]. After number 6: [1, 1, 1, 2, 2, 2, 3, 3, 2, 3, 3]. The answer is ways[10], 3.
Code
def count_sign_ways(nums, target):
total = sum(nums)
if abs(target) > total or (total + target) % 2:
return 0
want = (total + target) // 2 # the sum the numbers with a plus sign must reach
ways = [1] + [0] * want # ways[s]: subsets of the numbers seen so far with sum s
for x in nums:
for s in range(want, x - 1, -1):
ways[s] += ways[s - x]
return ways[want]Time and memory
O(n * P) time, which is at most O(n * total), one addition per number and sum. O(P) memory for the list.
Common mistakes
- Skipping the odd check. Integer halving then rounds down, and the list counts subsets for a sum that does not match the target.
- Going through the sums upward. A number can then be added into a sum more than once, which counts subsets that use one number twice.
- Treating zeros as nothing. Each zero doubles the count, and example 3 gives 8, not 1.