#494

Target Sum

specialist · 835 · lc medium +31 · verified · 51.9% accepted · 12,336 likes · top 41%

play →

Description

Given an integer array nums and an integer target, place a '+' or '-' before each number and compute the resulting sum. Return the total number of distinct sign assignments that produce exactly target.

Example 1:

Input: nums = [1,1,1,1,1], target = 3
Output: 5
Explanation: There are 5 ways to assign symbols to make the sum of nums be target 3.
-1 + 1 + 1 + 1 + 1 = 3
+1 - 1 + 1 + 1 + 1 = 3
+1 + 1 - 1 + 1 + 1 = 3
+1 + 1 + 1 - 1 + 1 = 3
+1 + 1 + 1 + 1 - 1 = 3

Example 2:

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

Code

1
2
3