#494

Target Sum

Medium 0/1 knapsack (count subsets)

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Put + or − in front of every number. Count the sign choices that make the expression equal target.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: ways to put + or − before each number to reach target.

Why this works: the plus group P must equal (total + target) / 2, so count subsets with that sum.

Example: [1, 1, 1, 1, 1], target 3 → P = 4

ways to choose 4 ones out of 5 → 5

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Missing zeros: each 0 doubles the count — the DP handles it naturally if dp[0] starts at 1 and you loop down to x (including s = x = 0).

Solve on LeetCode ↗
Complexity
  • Time: O(n · P).
  • Space: O(P).
Topic: Dynamic Programming
🎬 Episodes 86–96: video coming soon