Target Sum
1 approach, code in every language
Problem description
You are given an array of non-negative integers and an integer target. You must place either a plus sign or a minus sign in front of every number and then concatenate them into an arithmetic expression.
For example, with the numbers [2, 1] you could form +2+1, +2-1, -2+1, or -2-1. Each choice of signs yields one expression and one resulting value.
Return the number of distinct sign assignments that make the expression evaluate exactly to target.
Example 1
Input: nums = [1,1,1,1,1], target = 3
Output: 5
There are five ways to choose signs that sum to 3, each turning exactly one of the ones negative: -1+1+1+1+1, +1-1+1+1+1, and so on.
Example 2
Input: nums = [1], target = 1
Output: 1
Only assigning a plus sign to the single 1 reaches the target, so there is exactly one valid assignment.
Constraints
1 <= nums.length <= 200 <= nums[i] <= 10000 <= sum(nums) <= 10^4-1000 <= target <= 1000
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Thruster Burn Plans is our own problem on the technique behind Target Sum: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free