Target Sum

35 min · findTargetSumWays()

The same list of numbers can tell very different stories once every value gets a plus or a minus sign.

Given non-negative integers nums and an integer target, place either + or - before every array position. Return the number of distinct sign assignments whose final sum equals target.

Positions stay distinct even when their values match. A zero has two sign choices too: +0 and -0 produce the same sum, but they are different assignments and must both be counted.

A few ground rules:

  • Every position receives exactly one sign.
  • You return a count, not one arrangement of signs.
  • Every answer in the test suite is smaller than 2^31.

Constraints

  • 1 <= nums.length <= 20
  • 0 <= nums[i] <= 1_000
  • -1_000 <= target <= 1_000
  • The answer is smaller than 2^31.

Hints

Write the honest search first

At each position you have two branches: add the value or subtract it. The pair (position, running sum) captures everything the remaining choices need to know.

Two piles are hiding here

Let P be the sum of values given +, N the sum of values given -, and S the sum of all values. Then P - N = target and P + N = S.

Count instead of mark

Solving those equations gives P = (S + target) / 2. Use a subset-sum table whose cells store how many ways reach each sum, not just whether that sum is reachable.

Follow-up

How would you recover one valid sequence of signs when the returned count is nonzero?

Visible cases

Examples

Example 1

ready
Input
nums = [
  1,
  1,
  1,
  1,
  1
]
target = 3
Expected
5
Why
five different choices leave one 1 with a minus sign

Example 2

ready
Input
nums = [
  1
]
target = 1
Expected
1
Why
+1 reaches the target

Example 3

ready
Input
nums = [
  1
]
target = 2
Expected
0
Why
neither +1 nor -1 can reach 2

Interview signal

Asked at

AmazonGoogleMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite