Skip to content
BytePatterns

Signs That Hit a Target

MediumDynamic Programming#0-1-knapsack#subset-count~30m

Problem

Given a list of non-negative integers and a target, put a plus or a minus sign in front of every number and add them all up. Return how many different sign choices give exactly the target. A zero counts twice, since +0 and -0 are different choices.

Examples

Input:  nums = [1, 2, 3, 4], target = 2
Output: 2
Why:    -1 + 2 - 3 + 4 and 1 + 2 + 3 - 4 both give 2
Input:  nums = [0, 5], target = 5
Output: 2
Why:    +0 + 5 and -0 + 5 are different choices
Input:  nums = [3], target = 2
Output: 0
Why:    edge case, only 3 and -3 are possible

Hints

0 / 3

Stuck on the idea rather than the code? 0/1 Knapsack covers it.