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 numstargettarget
Example 1
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
Output: 1
Example 3
Output: 2
Explanation: -1 - 2 + 3 = 0 and +1 + 2 - 3 = 0.
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
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
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.
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
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
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
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 waysways[s]
The order of the update matters. When s goes from the plus sum down to v, the entry ways[s - v]
Java Solution
The method findTargetSumWays
- First, add up all the numbers into
with a loop overtotal .nums - Return 0 when
is bigger thanMath.abs(target) , or whentotal is odd, since no sign choice works then.total + target - Work out the plus sum,
, and create the arrayplus = (total + target) / 2 withways counts, for the sums 0 toplus + 1 . Setplus , for the empty group.ways[0] = 1 - Add the numbers one at a time with a loop that takes each number
fromv . Inside, a second loop movesnums froms down toplus and addsv toways[s - v] .ways[s] - After the last number,
counts the groups that reach the plus sum, which is the number of sign choices, and the method returns it.ways[plus]
The main
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:
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.abspluswaysNegativeArraySizeExceptionsv
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
+ 1 sums, with one addition each.plus - Space: O(plus), because the single
array holdsways + 1 counts in place of the full table in the picture, which has a row for every number.plus