AAlgoLoopSpaced repetition for LeetCode
MEDIUMDynamic ProgrammingLeetCode ↗

Target Sum

The key idea

Split nums into a positive group P (gets +) and a negative group N (gets -). Then sum(P) - sum(N) = target and sum(P) + sum(N) = total. Adding the two gives sum(P) = (target + total) / 2. So the answer is just the number of subsets of nums whose sum equals that fixed value S — a classic 0/1-knapsack subset-count. If target + total is odd or negative, the answer is 0.

Problem

You are given an integer array nums and an integer target.

You want to build an expression out of nums by adding one of the symbols + and - before each integer in nums, and then concatenate all the integers.

Return the number of different expressions that you can build, which evaluates to target. Each number in nums must receive exactly one symbol, and all numbers must be used.

Constraints

Examples

Input: nums = [1,1,1,1,1], target = 3 Output: 5
Input: nums = [1], target = 1 Output: 1
Input: nums = [1,2,3], target = 0 Output: 2

Complexity

Time: O(n * P) Space: O(P)

See the full solution

410310
Step-by-step visualization
Start free →

More Dynamic Programming problems