CodingNodes / 2-D Dynamic Programming / Target Sum System design Space play · ←→ step · R restart

Problem

You are given an array nums of non-negative integers and an integer target. Put either + or - in front of every number, then add them all up to get one value.

Return how many different sign choices produce exactly target. Two choices differ if at least one number gets a different sign, even when the numbers are equal.

Constraints

  • 1 ≤ nums.length ≤ 20
  • 0 ≤ nums[i] ≤ 1000
  • 0 ≤ sum(nums) ≤ 1000
  • −1000 ≤ target ≤ 1000

Examples: pick one to animate

Solutions

TimeO(n · (sum + target)) SpaceO(n · (sum + target))

Time: After the check, the table has n + 1 rows and about (sum + target) / 2 + 1 columns, and each cell takes constant work.

Space: The whole table is stored, which is the same number of cells.

Numbers with a plus sum to P, those with a minus sum to N. P - N = target and P + N = total, so P = (total + target) / 2. Counting sign choices becomes counting subsets that add to P. If that value is not a whole number or is out of range, the answer is 0. Otherwise dp[i][j] counts subsets of the first i numbers with sum j: leave number i out, or take it.