CodingNodes / 1-D Dynamic Programming / Partition Equal Subset Sum System design Space play · ←→ step · R restart

Problem

Given an array of positive integers nums, decide whether the numbers can be split into two groups that have the same sum. Every number must go into exactly one group.

Return true if such a split exists, otherwise false.

Constraints

  • 1 ≤ nums.length ≤ 6
  • 1 ≤ nums[i] ≤ 9

Examples: pick one to animate

Solutions

TimeO(n · target) SpaceO(target)

Time: Each of the n numbers updates up to target + 1 sums, where target is half the total.

Space: One boolean per sum from 0 to target.

Two equal groups mean one group sums to total / 2, so the total must be even. Then it is a subset-sum question. Let dp[s] be True if some of the numbers so far make sum s. For each number x, set dp[s] True whenever dp[s - x] is True. Loop the sums downward so each number is used only once.