Skip to contentKEEP THE CRAFTTHE SANCTUARY

Target Sum

Count how many ways to put + or - in front of every number so the total equals the target.

The problem

Implement Solution.findTargetSumWays(nums, target). Put either + or - in front of every number in nums, keeping their order, and add everything up. Return how many different sign choices give exactly target. A 0 still gets a sign, so + 0 and - 0 count as two different choices. nums has between 1 and 20 numbers, each between 0 and 1,000, their sum is at most 1,000, and target is between -1,000 and 1,000.

Starter code

class Solution:
    def findTargetSumWays(self, nums, target):
        pass

Public examples

  1. nums = [1, 1, 1, 1, 1], target = 3gives5
  2. nums = [3], target = -3gives1
  3. nums = [0], target = 0gives2

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.