Example 1
- Input
- nums = [1, 1, 1, 1, 1], target = 3
- Output
- 5
Exactly one position must carry a minus: -++++, +-+++, ++-++, +++-+, and ++++-. Each expression sums to 3; the five equal values still occupy five distinct positions.
Given an array of numbers and a target, count how many ways a plus or minus sign can be placed before each number so the resulting expression equals the target.
You are given an integer array nums and an integer target. Place either + or - before every element of nums, then evaluate the expression. Return the number of different sign assignments that evaluate to target.
For nums = [1, 1, 1, 1, 1] and target = 3, the answer is 5: the five expressions with four plus signs and one minus sign each total .
1 <= nums.length <= 200 <= nums[i] <= 10000 <= sum(nums) <= 1000-1000 <= target <= 1000Exactly one position must carry a minus: -++++, +-+++, ++-++, +++-+, and ++++-. Each expression sums to 3; the five equal values still occupy five distinct positions.
There are two complete assignments, +1 and -1. Only +1 equals 1, so count one.
The final 1 must have a plus. Each zero independently takes either sign: +0+0+1, +0-0+1, -0+0+1, and -0-0+1 are four distinct expressions with the same value.
The four expressions evaluate to 3, -1, 1, and -3. None equals zero. Equivalently, S + target = 3 is odd, so no integer plus-subset sum exists.
Only +1-2 reaches -1. Here S = 3 and the plus-group goal is (3 - 1) / 2 = 1, represented by the first position alone.
A sign belongs to an array position, so equal numbers and the two signs on zero remain separate choices. In Example 1 the five ones total 5; negating any one position reduces the total by twice that value, giving 3. A recursive search counts every complete choice. To avoid repeating work, group positions carrying a plus sign into a subset: if its sum is P and all numbers sum to S, then P - (S - P) = target. Thus we can count subsets of positions totaling (S + target) / 2 instead of constructing every expression.
Reveal Brute Force Recursion: intuition, complexity, and code
A binary sign choice can become subset counting when the two groups partition a fixed total. Derive the forced sum, reject impossible parity and range, and use a backward 0/1 count so positions, duplicates, and zeros retain their multiplicity.