Target Sum⚓︎
Description⚓︎
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 concatenate 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 that you can build, which evaluates to target
.
Example 1:
- Input:
nums = [1,1,1,1,1], target = 3
- Output:
5
- Explanation: There are
5
ways to assign symbols to make the sum of nums be target3
.
Example 2:
- Input:
nums = [1], target = 1
- Output:
1
Constraints:
1 <= nums.length <= 20
0 <= nums[i] <= 1000
0 <= sum(nums[i]) <= 1000
-1000 <= target <= 1000
Solution⚓︎
Way 1⚓︎
Way 2⚓︎
Mapping to Subset Sum Problem:
- Sum of all Elements: Let's denote the sum of all elements in
nums
assum
. - Partitioning into Two Subsets: Imagine splitting the
nums
array into two subsets,S1
andS2
, whereS1
contains elements with a '+' sign, andS2
contains elements with a '-' sign. Then, the problem boils down to finding subsetsS1
andS2
such thatsum(S1) - sum(S2) = target
. - Rearranging the Equation: Rearranging the equation, we get
sum(S1) = (target + sum(S2)) = (target + sum - sum(S1))
. Simplifying,2 * sum(S1) = target + sum
. -
Finding sum(S1): The problem now is to find a subset
S1
such thatsum(S1) = (target + sum) / 2
. This is a standard subset sum problem. -
Time Complexity: \(O(nm)\) where \(n\) is the number of elements in nums and \(m\) is
(sum + target) / 2
. - Space Complexity: \(O(nm)\) due to the 2D array.
Way 3⚓︎
- Time Complexity: Same as the 2D approach, \(O(nm)\).
- Space Complexity: \(O(m)\), a significant improvement over the 2D approach, as we are only using a single array of size \(m + 1\).