Target Sum (LeetCode 494): Solution and Explanation
You are given an array of non-negative integers and a target. Put either a plus or a minus sign in front of every number, then count how many sign assignments make the expression evaluate to the target.
Watch it run step by step
Try your own input and write the code →Intuition
The direct approach tries every sign choice: each number is either added or subtracted, so there are 2^n assignments, and a recursive search can evaluate them all. With up to 20 numbers that is about a million paths, which actually passes, and adding memoization on (index, running sum) makes it comfortably fast. But there is a cleaner way that turns the problem into something you already know.
Split the numbers into two groups: the ones that get a plus sign, with sum P, and the ones that get a minus sign, with sum N. The expression equals P - N, and every number lands in exactly one group, so P + N = total. Adding these two equations gives 2P = total + target, so P = (total + target) / 2. In other words, every valid sign assignment corresponds to exactly one subset of the numbers whose sum is (total + target) / 2, and vice versa.
That means the answer is the number of subsets with a particular sum, which is the classic 0/1 knapsack counting problem. If total + target is odd or negative, no such subset exists and the answer is 0. Otherwise keep an array dp where dp[j] counts the subsets seen so far that sum to j. Start with dp[0] = 1 for the empty subset. For each number, every existing subset that sums to j - num can be extended by that number to sum to j. Updating j from high to low ensures each number is used at most once per subset.
Approach: Subset-sum counting with a 1D DP
- Compute
total = sum(nums). - If
total + targetis odd or negative, return 0, because the required positive-group sum would not be a non-negative integer. - Set
subset_sum = (total + target) // 2and createdpof lengthsubset_sum + 1withdp[0] = 1. - For each
num, loopjfromsubset_sumdown tonum, addingdp[j - num]todp[j]. - The descending order means
dp[j - num]still holds the count from before this number was considered, so no number is reused. - Return
dp[subset_sum], the number of subsets, and therefore sign assignments, that reach the target.
Step-by-step example
nums = [1, 1, 1, 1, 1], target = 3
total = 5, and5 + 3 = 8is even, sosubset_sum = 4anddp = [1, 0, 0, 0, 0].- After the first 1,
dp = [1, 1, 0, 0, 0]. After the second,dp = [1, 2, 1, 0, 0]. - After the third 1,
dp = [1, 3, 3, 1, 0]. After the fourth,dp = [1, 4, 6, 4, 1]. - After the fifth 1,
dp = [1, 5, 10, 10, 5]. - The function returns
dp[4] = 5. That matches the five ways to choose which single 1 gets the minus sign.
Code: Python, Java, C++
1class Solution:
2 def findTargetSumWays(self, nums: List[int], target: int) -> int:
3 total = sum(nums)
4
5 # (total + target) must be even and non-negative
6 if (total + target) % 2 != 0 or total + target < 0:
7 return 0
8
9 subset_sum = (total + target) // 2
10 dp = [0] * (subset_sum + 1)
11 dp[0] = 1
12
13 for num in nums:
14 for j in range(subset_sum, num - 1, -1):
15 dp[j] += dp[j - num]
16
17 return dp[subset_sum]1class Solution {
2 public int findTargetSumWays(int[] nums, int target) {
3 int sum = 0;
4 for (int num : nums) sum += num;
5
6 // (sum + target) must be even and non-negative
7 if ((sum + target) % 2 != 0 || sum + target < 0) return 0;
8
9 int subsetSum = (sum + target) / 2;
10 int[] dp = new int[subsetSum + 1];
11 dp[0] = 1;
12
13 for (int num : nums) {
14 for (int j = subsetSum; j >= num; j--) {
15 dp[j] += dp[j - num];
16 }
17 }
18 return dp[subsetSum];
19 }
20}1class Solution {
2public:
3 int findTargetSumWays(vector<int>& nums, int target) {
4 int sum = 0;
5 for (int num : nums) sum += num;
6
7 // (sum + target) must be even and non-negative
8 if ((sum + target) % 2 != 0 || sum + target < 0) return 0;
9
10 int subsetSum = (sum + target) / 2;
11 vector<int> dp(subsetSum + 1, 0);
12 dp[0] = 1;
13
14 for (int num : nums) {
15 for (int j = subsetSum; j >= num; j--) {
16 dp[j] += dp[j - num];
17 }
18 }
19 return dp[subsetSum];
20 }
21};Time and space complexity
O(n × S)
S is (total + target) / 2. For each of the n numbers, the inner loop runs over at most S + 1 sums with constant work per sum.
O(S)
Only the single dp array of length S + 1 is kept, because each row of the knapsack table depends only on the previous row and the backward loop reuses it in place.
Other approaches
DFS with memoization (time O(n × total), space O(n × total))
Recurse on (index, current sum), trying plus and minus for each number, and cache results in a dictionary. It follows the problem statement directly and needs no algebra, but it stores a state for every reachable sum at every index.
Plain backtracking (time O(2^n), space O(n))
Try both signs for every number without caching and count the paths that end at the target. It is the easiest to write and passes for n up to 20, but it grows exponentially.
Common mistakes
- Looping
jupward in the 1D DP. That lets a number be added to a subset that already includes it, which counts combinations with repetition. - Skipping the parity and sign check. If
total + targetis odd or negative, integer division silently produces a wrong subset sum, and a negative size crashes the array allocation. - Mishandling zeros. A 0 can be +0 or -0, doubling the count. The reference loop handles it because for
num = 0the range includesj = 0, sodp[0]doubles; a loop that stops atj = 1would miss this. - Not guarding against
abs(target) > totalin other languages. The reference code handles it implicitly sincedp[subset_sum]stays 0, but some variants index out of range.
Frequently asked questions
How does Target Sum become a subset sum problem?
If P is the sum of numbers with plus signs and N the sum with minus signs, then P - N equals the target and P + N equals the total. Solving gives P = (total + target) / 2, so you count subsets with that sum.
Why does the inner loop go from high to low?
Going backward means dp[j - num] has not yet been updated for the current number, so each number contributes to a subset at most once. Going forward would turn it into an unbounded knapsack.
Is backtracking fast enough for Target Sum?
With at most 20 numbers, 2^20 is about a million paths, so plain backtracking usually passes. The DP is still preferred because it scales with the sum instead of exponentially with n.