MediumArrayDynamic ProgrammingBacktracking

Target Sum

LeetCode
1 approach, code in all languages

You are given an array of non-negative integers and an integer target. You must place either a plus sign or a minus sign in front of every number and then concatenate them into an arithmetic expression.

For example, with the numbers [2, 1] you could form +2+1, +2-1, -2+1, or -2-1. Each choice of signs yields one expression and one resulting value.

Return the number of distinct sign assignments that make the expression evaluate exactly to target.

Example 1

Input: nums = [1,1,1,1,1], target = 3

Output: 5

There are five ways to choose signs that sum to 3, each turning exactly one of the ones negative: -1+1+1+1+1, +1-1+1+1+1, and so on.

Example 2

Input: nums = [1], target = 1

Output: 1

Only assigning a plus sign to the single 1 reaches the target, so there is exactly one valid assignment.

Constraints

  • 1 <= nums.length <= 20
  • 0 <= nums[i] <= 1000
  • 0 <= sum(nums) <= 10^4
  • -1000 <= target <= 1000
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now