Target sum
Challenge · Write code · about 20 min
Put a + or a − in front of every number in nums, then add them all up. Return how many sign choices give exactly target.
Example 1
Input:
[[1,1,1,1,1],3]
Output:
5
One of the five 1s gets a minus sign; any of the five can be chosen.
Example 2
Input:
[[1],1]
Output:
1
+1 is the only way.
Constraints
- 1 ≤ nums.length ≤ 20
- 0 ≤ nums[i] ≤ 40
- target is any integer; return 0 when no sign choice reaches it
Learn the idea first: 0/1 and unbounded knapsack, a visual lesson.
More 0/1 and unbounded knapsack problems
- Fill the knapsack table Warm-up
- Take or skip? Warm-up
- 0/1 knapsack Standard
- Partition equal subset sum Standard
- Unbounded knapsack Standard
- Spot the bug: one-row 0/1 knapsack Standard