← DiffPush

Target Sum

Standard Bar Dynamic Programming · DP on Subsequences O(n*S) · O(S)

The Sensor Pairing Dip Switch

A calibration rig flips each of n sensor channels into either an amplifying or an attenuating mode before a measurement run. The lab needs the combined gain to land exactly on a target offset, and the technician counts how many switch assignments achieve it. Channels with identical ratings are still independent hardware, so each assignment counts separately.

Input: An array nums of n non-negative integers and an integer target.

Output: Return the number of ways to assign + or - signs so the signed sum equals target.

Constraints

Examples

Example 1

Input: {"nums":[1,1,1,1,1],"target":3}
Output: 5
Exactly one channel attenuates (five choices); each gives 4 - 1 = 3.

Example 2

Input: {"nums":[1],"target":1}
Output: 1
The single channel must amplify: +1.

Solve this in your browser →

Also on LeetCode ↗