You are given a list of non-negative whole numbers, nums, and a number target. Put a plus or a minus sign in front of every number, keep the order, and add them all up. For [3, 5], the choices +3 −5 give −2.
Return how many of the sign patterns add up to exactly target. Two patterns count as different when at least one number has a different sign, even if that number is 0.
Example 1
Input: nums = [1, 2, 1], target = 2 Output: 2 Why: +1 +2 −1 = 2 and −1 +2 +1 = 2
2 more examples and the constraints
Example 2
Input: nums = [3], target = -3 Output: 1 Why: only −3 works
Example 3
Input: nums = [2, 2, 2], target = 1 Output: 0 Why: a sum of even numbers is always even
Constraints
- 1 ≤ length of nums ≤ 20
- 0 ≤ each number ≤ 1,000
- The numbers add up to at most 1,000
- −1,000 ≤ target ≤ 1,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Try every signO(2ⁿ)
- Memoised recursionO(n·S)
- Count subsets (0/1 knapsack)O(n·S)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 20 numbers adding up to 1,000 | Verdict |
|---|---|---|---|
| Try every sign | O(2ⁿ) | Mention it, then move on | |
| Memoised recursion | O(n·S) | Passes; a cache on the brute force | |
| Count subsets (0/1 knapsack) | O(n·S) | Best; one small row |
n = how many numbers, S = their sum.
Edge cases to test
- Zeros. +0 and −0 are different patterns, so each zero doubles the count: [0, 0, 1] with target 1 gives 4.
- Odd total + target. Then the plus group would need a half-integer sum, so the answer is 0.
- Target out of reach. If |target| is more than the total, return 0 before building a table with a negative size.
- Negative target. The goal (total + target) / 2 is smaller but still valid: [4, 1, 2] with −3 has goal 2.
Common mistakes
- Looping s upwards in the one-row table, which lets one number join a group twice.
- Forgetting the |target| > total check, so the goal is negative and the table breaks.
- Skipping zeros or treating +0 and −0 as one choice.
How to talk through it
- 1Clarify. Can numbers be 0? Does +0 differ from −0? Can the target be negative or larger than the sum?
- 2Give the brute force. Branch on + and − for every number: 2ⁿ patterns.
- 3Spot the repeats. A call depends only on (i, total), so a memo brings it to O(n·S).
- 4Turn it into subset sum. P − M = target and P + M = total give P = (total + target) / 2; count groups with that sum in one row.
- 5Test out loud. Run a case with zeros and one where total + target is odd before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?