Facebook Pixel

You are on level: Student

0%
Expand section
Expand section
Expand section
Expand section
Expand section
Expand section
Expand section
Expand section
Expand section
Expand section
Expand section

Target Sum

Given an integer array nums and an integer target, return the number of ways to assign + or - to each element such that the sum equals target. All values in nums are non-negative integers; the + or - is the sign you assign to each element, not the element's original sign.

Two assignments are different if any single element receives a different sign, even when the two assignments pick equal values sitting at different positions.

Input & Output
Input
nums — the array of non-negative integers to sign
target — the sum the signed elements must reach
Output
the number of sign assignments whose total equals target
Example
Input
nums = [1, 1, 1, 1, 1]
target = 3
Output
5
Explanation

Exactly one element must be negative: -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. The five ones are equal in value but sit at different positions, so the five assignments count separately.

Example
Input
nums = [1, 2, 3]
target = 6
Output
1
Explanation

The total of all elements is 6, so every element has to take a + sign. Flipping any one of them drops the sum by twice that element and overshoots downward, so +1+2+3 is the only assignment that works.

Constraints
  • 1 <= nums.length <= 20
  • 0 <= nums[i] <= 1000
  • 0 <= sum(nums) <= 1000
  • -1000 <= target <= 1000

Try it yourself

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro