Loading problem...
You are given an array of non-negative integers nums and an integer target. Your task is to determine how many distinct ways you can assign a sign (either + or -) to each element in the array such that the sum of all the signed values equals the given target.
Each element in the array must receive exactly one sign, and you must use all elements to form the expression. The order of elements in the expression follows their original order in the array.
Expression Construction:
nums, you prepend either a + or - signFor instance, if nums = [3, 2], you can form these expressions:
+3 + 2 = 5+3 - 2 = 1-3 + 2 = -1-3 - 2 = -5Return the total count of different sign assignments that produce a sum equal to target.
nums = [1,1,1,1,1]
target = 35There are exactly 5 distinct ways to assign signs such that the expression evaluates to 3: • -1 + 1 + 1 + 1 + 1 = 3 • +1 - 1 + 1 + 1 + 1 = 3 • +1 + 1 - 1 + 1 + 1 = 3 • +1 + 1 + 1 - 1 + 1 = 3 • +1 + 1 + 1 + 1 - 1 = 3
In each case, exactly one element receives a negative sign, and the remaining four elements are positive, yielding a sum of 3.
nums = [1]
target = 11With only one element, you have two possible expressions: +1 = 1 and -1 = -1. Only the expression +1 = 1 matches the target, so the answer is 1.
nums = [1,0]
target = 12The presence of zero in the array creates multiple valid combinations because +0 and -0 both equal 0. The valid expressions are: • +1 + 0 = 1 • +1 - 0 = 1
Both expressions evaluate to 1, giving us 2 distinct ways. Note that -1 + 0 = -1 and -1 - 0 = -1, neither of which equals 1.
Constraints