Skip to content

Target Sum

MediumDynamic Programming
Decode it first. Clues, constraints, pattern and plan before any code.

You are given an integer array nums and an integer target. Put either a + or a - sign in front of every number, then add them all up. Return the number of different sign assignments that make the total equal target.

nums = [1, 1, 1, 1, 1], target = 3  →  5   (one of the five 1s gets a minus)
nums = [1], target = 1              →  1
nums = [0, 0, 0], target = 0        →  8   (each 0 can be + or -)

Constraints

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