Solve subset-sum: find subset summing to target
You are given an array nums of positive integers and a positive integer target. Return a subset of nums whose values add up to exactly target.
Each index of nums may be used at most once, so a value that appears k times can appear at most k times in the answer. Return the chosen values ordered by the index they came from, smallest index first. Return an empty array when no subset adds up to target.
The task is a witness problem, not a decision problem: [5] and [1, 4] are equally valid answers for nums = [1, 5, 4] and target = 5, both standing in for the same subset question. Section "Choosing one answer" fixes which of the valid witnesses the grader expects.
Choosing one answer
Several subsets can reach the same target, and every answer is compared element by element. The expected answer is the one subset selected by this rule:
- Start with
rest = targetand allow every index ofnums. - While
rest > 0, scan the allowed indices from left to right and select the first indexifor whichrest - nums[i]can be formed using only the indices strictly beforei. A remainder of0is always formable, so an element equal torestis selectable. - Subtract
nums[i]fromrestand keep only the indices beforeifor the remaining steps. - Output the selected values in the reverse of the order they were selected, which lists them by ascending source index.
An equivalent description: among all valid subsets, keep the one whose largest source index is as small as possible; among those, the one whose second largest index is as small as possible, and so on.
Solve subset-sum: find subset summing to target
You are given an array `nums` of positive integers and a positive integer `target`. Return a subset of `nums` whose values add up to exactly `target`.