Target Sum
Difficulty: Medium · Pattern: 2-D Dynamic Programming · LeetCode #494
Put a + or a - in front of each number in nums, then evaluate the expression. Return the number of ways to make it equal target.
Examples
text
nums = [1,1,1,1,1], target = 3 → 5
nums = [1], target = 1 → 1Hints
- Let P be the sum of the numbers with
+and N the sum of those with−. ThenP − N = targetandP + N = total. - So
P = (total + target) / 2. Count the subsets with that sum.
Approach
Algebra turns it into subset-count DP: P = (total + target)/2 must be a non-negative integer, otherwise the answer is 0. Then run 0/1 knapsack counting:
text
dp[0] = 1
for x in nums:
for s in P down to x: dp[s] += dp[s - x]Iterating s downward ensures each number is used at most once. Zeros are handled naturally: a 0 doubles the count, since +0 and −0 are both valid.
A direct alternative is a DP over a hash map of reachable sums, {sum: ways}. It's O(n · range).
Complexity
Time: O(n · P). Space: O(P).
Python solution
def findTargetSumWays(nums, target):
total = sum(nums)
if abs(target) > total or (total + target) % 2:
return 0
P = (total + target) // 2
dp = [1] + [0] * P
for x in nums:
for s in range(P, x - 1, -1):
dp[s] += dp[s - x]
return dp[P]JavaScript solution
function findTargetSumWays(nums, target) {
let ways = new Map([[0, 1]]);
for (const x of nums) {
const next = new Map();
for (const [s, w] of ways) {
next.set(s + x, (next.get(s + x) || 0) + w);
next.set(s - x, (next.get(s - x) || 0) + w);
}
ways = next;
}
return ways.get(target) || 0;
}