Target Sum

Difficulty: Medium

Given a list of non-negative integers and a target, put a + or - sign in front of every number and add them up. Count the sign assignments whose total equals the target.

Examples

Input: nums = [1,1,1,1,1], target = 3
Output: 5

The five sign assignments that total 3 are: -1+1+1+1+1, +1-1+1+1+1, +1+1-1+1+1, +1+1+1-1+1, +1+1+1+1-1.

Input: nums = [1], target = 1
Output: 1

Only +1 works.

Constraints

  • 1 <= nums.length <= 20

  • 0 <= nums[i] <= 1000

  • 0 <= sum(nums) <= 1000

  • -1000 <= target <= 1000

Approach

Assigning signs splits the numbers into a positive group (sum P) and a negative group (sum total - P, where total is the sum of all numbers). The result must equal the target, so P - (total - P) = target, which gives P = (total + target) / 2.

Now it's plain subset counting: how many subsets of nums sum to P? Cell (i, s) is the number of subsets of the first i numbers that sum to s. Each number is either left out (the count with one fewer number) or included (the count for the remaining sum with one fewer number, since each number is used at most once).

If (total + target) is odd, or the target's absolute value exceeds the total, no split works, so the answer is 0.

Solutions

Brute Force — Recursion

Recursively try + and - for every number, and count the assignments that hit the target.

function findTargetSumWays(nums, target) {
  function solve(i, total) {
    if (i === nums.length) return total === target ? 1 : 0;
    return solve(i + 1, total + nums[i]) + solve(i + 1, total - nums[i]);
  }
  return solve(0, 0);
}

Time: O(2^n) · Space: O(n) — recursion depth

Optimal — Subset-Sum Counting with a 2D Table

Turn sign assignment into counting subsets that sum to P, then fill a standard subset-sum count table indexed by (numbers considered, running sum).

function findTargetSumWays(nums, target) {
  const total = nums.reduce((sum, x) => sum + x, 0);
  if (Math.abs(target) > total || (total + target) % 2 !== 0) return 0;

  const subsetSum = (total + target) / 2;
  const n = nums.length;
  const table = Array.from({ length: n + 1 }, () => new Array(subsetSum + 1).fill(0));
  table[0][0] = 1;

  for (let i = 1; i <= n; i++) {
    for (let s = 0; s <= subsetSum; s++) {
      table[i][s] = table[i - 1][s]; // leave nums[i - 1] out of the subset
      if (s - nums[i - 1] >= 0) {
        table[i][s] += table[i - 1][s - nums[i - 1]]; // include nums[i - 1] in the subset
      }
    }
  }

  return table[n][subsetSum];
}

Time: O(n * (total + target)) · Space: O(n * (total + target))