Target Sum

MediumDynamic Programming · 0/1 Knapsack (Count)🧩 Knapsack DPLeetCode #494 ↗Updated

Problem

Put a + or a - sign in front of every number of nums (keeping their order) to form an expression. Count how many different sign assignments make the expression evaluate to exactly target.
Input[1,1,1,1,1], target=3Output5
Input[1], target=1Output1

1 ≤ n ≤ 20  ·  0 ≤ nums[i] ≤ 1000  ·  sum(nums) ≤ 1000  ·  |target| ≤ 1000

Try it yourself

Java
class Solution {
    public int findTargetSumWays(int[] nums, int target) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Let P = numbers with +, N = with -. Then P - N = target and P + N = total, so P = (total + target) / 2. Just count subsets summing to P.
PatternKnapsack DP

Instinct Choose items to hit or stay under a target sum (can it be done, best value, fewest items, how many ways) - index a DP array by the remaining capacity.

Memory hack Once? Walk back. Many? Walk forward. Each item used at most once loops capacity downward; reusable items loop it upward.

Open the Knapsack DP guide →

Approaches

Brute ForceTry Every Sign (Recursion)

Time O(2n)Space O(n)

At index i branch twice: add nums[i] or subtract it. At the end, count 1 if the running sum equals target. Explores all 2n sign patterns.

Java
public int findTargetSumWays(int[] nums, int target) {
    return count(nums, 0, 0, target);
}
private int count(int[] nums, int i, int sum, int target) {
    if (i == nums.length) return sum == target ? 1 : 0;
    return count(nums, i + 1, sum + nums[i], target)
         + count(nums, i + 1, sum - nums[i], target);
}

Fine for n = 20 (~106 leaves), but doesn't scale.

At a glance

LevelApproachTimeSpace
Brute ForceTry Every Sign (Recursion)O(2n)O(n)
BetterMemoization on (index, running sum)O(n·T)O(n·T)
OptimalSubset-Count Knapsack (1-D)O(n·P)O(P)
Common pitfalls
  • Negative target: check |target| > total, not target > total.
  • Forgetting the parity check — (total+target)/2 rounds and overcounts.
  • Memo indexed by raw sum — negative index; shift by total.
Interview tips
  • Start with the 2n recursion (n ≤ 20 makes it acceptable), then memoize.
  • Derive P = (total + target)/2 on the whiteboard — it's the key step.
  • Point out it's the counting twin of Partition Equal Subset Sum.
Pattern
± signs → subset sum → split into a plus-set and a minus-set, then count subsets with 0/1 knapsack.
My notes saved in this browser