Menu
CoddyTech

Target Sum

You get an array nums of non-negative integers and an integer target. Put a plus or a minus sign in front of every number, keep their order, and evaluate the expression. Return how many sign choices make the expression equal target. Every one of the 2^n choices counts on its own, so +0 and -0 are two different choices.

Function

findTargetSumWays(nums: integer-array, target: integer) → integer
numsinteger-array
the numbers, each of which gets a sign
targetinteger
the value the expression must equal
Returnsinteger
the number of sign choices whose expression equals target

Constraints

  • 1 ≤ nums.length ≤ 20
  • 0 ≤ nums[i] ≤ 1000
  • The sum of nums is at most 1000.
  • -1000 ≤ target ≤ 1000
  • The answer is at most 220, well inside a 32-bit signed integer.

Examples

Input
nums = [2, 1, 1]target = 2
Output
2
Explanation
+2 +1 -1 and +2 -1 +1 both equal 2. With a minus on the 2, the most you can reach is -2 + 1 + 1 = 0, so no other choice works.
challenge icon

Follow-up

Can you handle up to 40 numbers with values up to 10^9, where no array indexed by the sum fits in memory?

Reset code
def findTargetSumWays(nums, target):
    # Write code here

Test #1

Test #2

Test #3

Arguments

nums = [2, 1, 1]
target = 2

Expected Output

2