You are given an integer array nums and an integer target.
You want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenating all the integers. For example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them to build the expression "+2-1".
Return the number of different expressions you can build that evaluate to target.
Function Signature
def find_target_sum_ways(nums: list[int], target: int) -> int:
Rules
-
The integers keep their order. Only the sign in front of each one is chosen.
-
Each way of assigning signs to the positions is one expression, so there are
2^n
expressions in total for
n
numbers. For example,
+0
and
-0
at the same position give two different expressions with the same value.
Constraints
-
1 <= len(nums) <= 20
-
0 <= nums[i] <= 1000
-
0 <= sum(nums) <= 1000
-
-1000 <= target <= 1000
Examples
Input: nums = [1, 1, 1, 1, 1], target = 3
Output: 5
Exactly one of the five 1s must get a minus sign: -1+1+1+1+1, +1-1+1+1+1, +1+1-1+1+1, +1+1+1-1+1 and +1+1+1+1-1.
Input: nums = [1], target = 1
Output: 1
Only the expression "+1" evaluates to 1.
Input: nums = [0, 0, 1], target = 1
Output: 4
The 1 must be positive, and each 0 can take either sign without changing the value. The four expressions are +0+0+1, +0-0+1, -0+0+1 and -0-0+1.