Target Sum Problem
Description
LeetCode Problem 494.
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 target 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
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
Approach: Reduce to Counting Subsets (0/1 Knapsack)
Trying every sign takes O(2n) time. A little algebra turns the problem into a subset count instead.
Call the numbers that get a + the group P, and those that get a - the group N. Then sum(P) - sum(N) = target, and sum(P) + sum(N) = total, the sum of all of nums. Adding the two equations gives sum(P) = (total + target) / 2. Every expression corresponds to exactly one choice of P, so the answer is the number of subsets of nums whose sum is goal = (total + target) / 2.
- If
|target| > total, ortotal + targetis odd, no subset works: return 0. - Let
ways[s]be the number of subsets of the numbers seen so far that sum tos. Start withways[0] = 1(the empty subset). - For each
num, updateways[s] += ways[s - num]forsfromgoaldown tonum.
The downward loop is the detail that matters: going upward would read ways[s - num] after it already includes num, using the same number twice. Zeros need no special case. For num = 0 the update doubles every count, which is right, because +0 and -0 are two different expressions.
For nums = [1,1,1,1,1] and target = 3, goal = (5 + 3) / 2 = 4: choose which four 1s get a +, which gives 5 ways.
Complexity: O(n · total) time and O(total) space, where n is the length of nums and total is its sum.
class Solution:
def findTargetSumWays(self, nums: List[int], target: int) -> int:
total = sum(nums)
# Split nums into a "+" group P and a "-" group N: P - N = target and P + N = total,
# so P = (total + target) / 2. Count the subsets of nums with that sum.
if abs(target) > total or (total + target) % 2 == 1:
return 0
goal = (total + target) // 2
ways = [0] * (goal + 1) # ways[s]: number of subsets seen so far that sum to s
ways[0] = 1
for num in nums:
# Go from high to low so each number is used at most once.
for s in range(goal, num - 1, -1):
ways[s] += ways[s - num]
return ways[goal]
Now write it from memory
Close the write-up and solve it yourself against the tests.