Skip to content
ΣDSA Patterns
Menu
Language

Knapsack & Subset DP

Guide 3 of 6 · Path 3 of 6

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Target Sum

Problem (restated)

Assign + or - to each nums[i]. Count ways the signed sum equals target.

Intuition

Partition into positive set P and negative set N: P-N=target, P+N=sum ⇒ P=(sum+target)/2. Count subsets summing to P.

Approaches

Subset-sum count reduction

Tested only
Time O(n·Σ)Space O(Σ)

Idea. If sum+target odd or |target|>sum → 0. 0/1 knapsack counting combinations.

Walkthrough. [1,1,1,1,1], target=3 → 5 ways.

Trade-offs. DFS with memo on (i, sum) also works; knapsack is O(nΣ).

Solution
export function findTargetSumWays(nums: number[], target: number): number {
  const total = nums.reduce((a, b) => a + b, 0);
  if (total < Math.abs(target) || (total + target) % 2 !== 0) return 0;
  const need = (total + target) / 2;
  const dp = Array(need + 1).fill(0);
  dp[0] = 1;
  for (const x of nums) {
    for (let c = need; c >= x; c--) dp[c] += dp[c - x]!;
  }
  return dp[need]!;
}
export function findTargetSumWays(nums: number[], target: number): number {
  const total = nums.reduce((a, b) => a + b, 0);
  if (total < Math.abs(target) || (total + target) % 2 !== 0) return 0;
  const need = (total + target) / 2;
  const dp = Array(need + 1).fill(0);
  dp[0] = 1;
  for (const x of nums) {
    for (let c = need; c >= x; c--) dp[c] += dp[c - x]!;
  }
  return dp[need]!;
}

Template connection

Subset-sum / 0/1 knapsack counting.

Reflection