Target Sum

Count the ways to put a plus or minus sign before each number so that the result equals a target.

Given an array of non-negative integers nums and an integer target, put a + or a - sign in front of every number and work out the result. Return how many different sign choices make the result equal to target.

Example 1
Input: nums = [1, 1, 1, 1, 1], target = 3
Output: 5
Explanation: one of the five 1s gets a - sign and the rest get +, for example -1 + 1 + 1 + 1 + 1 = 3.
Example 2
Input: nums = [1], target = 1
Output: 1
Example 3
Input: nums = [1, 2, 3], target = 0
Output: 2
Explanation: -1 - 2 + 3 = 0 and +1 + 2 - 3 = 0.
Solution

The Idea

Picture a balance scale and three weights of 1, 2 and 3 kilograms. Each weight goes on the left pan or the right pan. A weight on the left counts with a + sign, a weight on the right with a - sign, and target says how much heavier the left pan must be. Example 3 asks for a perfect balance, a difference of 0.

Three weights can be placed in 2 × 2 × 2 = 8 ways, and two of them balance: 3 alone against 1 and 2, or 1 and 2 against 3 alone. Example 1 has five weights of 1, so 32 ways, and five of them leave the left pan 3 kilograms heavier. Every extra number doubles the count, and 20 numbers already give 1,048,576 sign choices. Can the good ones be counted without trying them all?

Now give the two pans a name each. Call the sum of the numbers with a + sign the plus sum, and the sum of the numbers with a - sign the minus sum. Together they make the total of all the numbers, and their difference is target. In Example 3 the total is 6 and the difference 0, so each pan holds 3. In Example 1 the total is 5 and the difference 3, so the plus sum is 4 and the minus sum 1.

So the plus sum is fixed by the input: it is always (total + target) / 2. The sign question becomes a counting question: how many groups of the numbers add up to the plus sum? Each such group gets the + signs, and every other number gets a - sign. In Example 1 the group is four of the five 1s, and there are 5 ways to choose the 1 that is left out.

How do we count those groups? Add the numbers one at a time, and keep, for every sum from 0 up to the plus sum, how many groups of the numbers added so far reach that sum. Look at the picture below, made for Example 3, where the plus sum is 3.

A table for nums = [1, 2, 3] with one row per number added and columns sum 0 to sum 3. The rows read 1, 0, 0, 0; then 1, 1, 0, 0 after 1; then 1, 1, 1, 1 after 2; then 1, 1, 1, 2 after 3. The last entry, 2, is the 1 above it (groups without 3) plus the 1 in column sum 0 of the row after 2 (groups with 3).

In the row labelled no numbers yet, the empty group is the one group there is, and it adds up to 0, so that row reads 1, 0, 0, 0. In the row labelled after 1, the sum 1 can be reached too. Now look at the orange box, in column sum 3 of the row labelled after 3. A group of 1, 2 and 3 that adds up to 3 either leaves the 3 out or takes it.

Groups that leave the 3 out already make 3 without it, and the blue box above counts them: one group, 1 + 2. Groups that take the 3 need the rest to make 3 - 3 = 0, and the teal box counts those: one group, the empty one, so the 3 stands alone. That gives 1 + 1 = 2, the answer to Example 3.

Each row is built only from the row above it, so no sign choice is ever tried twice. Counting with a table like this one, where each new row reuses the counts of the row above, is called dynamic programming.

Solution Approach

Trying every sign choice works but is slow, so the code settles three things instead: the sum the plus group must reach, how each new number updates the counts, and how to keep all the counts in one array.

Trying every sign choice

What would the direct way look like? A method takes the numbers in order and, for each one, calls itself twice, once with a + sign and once with a - sign. At the end of each path it checks whether the result equals target. That is 32 paths for Example 1, and the number of paths doubles with every number in the array.

The sum the plus group must reach

Which sum must the plus group reach? The plus sum and the minus sum add up to the total, and the plus sum minus the minus sum is target. Adding these two facts gives twice the plus sum = total + target, so the plus sum is half of total + target.

Two cases have no answer at all. If total + target is odd, the plus sum is not a whole number: five 1s with target 2 would need a plus sum of 3.5. If target is further from 0 than the total, even all + signs or all - signs fall short: [1, 2] reaches at most 3 and at least -3, so target -11 is out of reach. In both cases the answer is 0.

How a new number updates the counts

What happens to the counts when the next number, call it v, is added? A group that reaches a sum s either skips v or takes it. The groups that skip v are the count for s from before. The groups that take v need the rest to reach s - v, which is the count for s - v from before. So the new count for s is the sum of those two counts, for every s from v up to the plus sum.

Sums smaller than v cannot take v, so their counts stay as they are. A 0 in the array doubles every count, because +0 and -0 are two different sign choices with the same result.

Keeping the counts in one array

Does the table need a separate row for every number? Each row reads only the row above, so one array, named ways, can hold the current row and be updated in place. Then ways[s] is the number of groups of the numbers added so far that reach the sum s.

The order of the update matters. When s goes from the plus sum down to v, the entry ways[s - v] sits at a smaller index that has not been updated yet, so it still holds the count from before v. Going up instead, that entry may already include v, and v would be used twice in one group.

Java Solution

The method findTargetSumWays works in these steps:

  1. First, add up all the numbers into total with a loop over nums.
  2. Return 0 when Math.abs(target) is bigger than total, or when total + target is odd, since no sign choice works then.
  3. Work out the plus sum, plus = (total + target) / 2, and create the array ways with plus + 1 counts, for the sums 0 to plus. Set ways[0] = 1, for the empty group.
  4. Add the numbers one at a time with a loop that takes each number v from nums. Inside, a second loop moves s from plus down to v and adds ways[s - v] to ways[s].
  5. After the last number, ways[plus] counts the groups that reach the plus sum, which is the number of sign choices, and the method returns it.

The main method runs the three examples, Example 1 again with target -3, five 1s with the odd case target 2, the array [0, 0, 1] with target 1, and [1, 2] with the out-of-reach target -11.

Java
public class TargetSum {

    public static int findTargetSumWays(int[] nums, int target) {
        int total = 0;
        for (int v : nums) {
            total += v;
        }
        // plus - minus = target and plus + minus = total, so plus = (total + target) / 2
        if (Math.abs(target) > total || (total + target) % 2 != 0) {
            return 0;
        }
        int plus = (total + target) / 2;
        int[] ways = new int[plus + 1];      // ways[s]: groups so far that sum to s
        ways[0] = 1;                         // the empty group
        for (int v : nums) {
            for (int s = plus; s >= v; s--) {
                ways[s] += ways[s - v];      // groups without v, plus groups with v
            }
        }
        return ways[plus];
    }

    public static void main(String[] args) {
        System.out.println(findTargetSumWays(new int[] {1, 1, 1, 1, 1}, 3));
        System.out.println(findTargetSumWays(new int[] {1}, 1));
        System.out.println(findTargetSumWays(new int[] {1, 2, 3}, 0));
        System.out.println(findTargetSumWays(new int[] {1, 1, 1, 1, 1}, -3));
        System.out.println(findTargetSumWays(new int[] {1, 1, 1, 1, 1}, 2));
        System.out.println(findTargetSumWays(new int[] {0, 0, 1}, 1));
        System.out.println(findTargetSumWays(new int[] {1, 2}, -11));
    }
}

Running it prints:

Output
5
1
2
5
0
4
0

The first three lines, 5, 1 and 2, match the three examples. The fourth line is 5 as well: with target -3 the plus sum is 1, so one 1 gets a + sign, and each answer for 3 turns into an answer for -3 by flipping every sign.

The fifth line, 0, comes from the odd check. Without it, integer division rounds 3.5 down to 3, and the method returns 10, the number of ways to pick three of the five 1s. The sixth line is 4 for [0, 0, 1]: the 1 must take +, and each 0 can take either sign, so 2 × 2 choices.

The last line is 0 for target -11. Without the Math.abs check, plus would be -4, and creating ways throws a NegativeArraySizeException. The direction of the inner loop matters too. Turned around, so that s goes up from v, it returns 3 for Example 3 instead of 2. After the 1, the counts already read 1, 1, 1, 1, as if 1 + 1 and 1 + 1 + 1 were groups.

Complexity

The work is one pass to add up the numbers, then one pass over the counts for each number.

  • Time: O(n × plus), because each of the n numbers runs the inner loop over at most plus + 1 sums, with one addition each.
  • Space: O(plus), because the single ways array holds plus + 1 counts in place of the full table in the picture, which has a row for every number.

Partition Equal Subset Sum asks a close question, whether some group of the numbers adds up to half the total, and fills the same kind of array with true and false instead of counts.