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:

  1. Start with rest = target and allow every index of nums.
  2. While rest > 0, scan the allowed indices from left to right and select the first index i for which rest - nums[i] can be formed using only the indices strictly before i. A remainder of 0 is always formable, so an element equal to rest is selectable.
  3. Subtract nums[i] from rest and keep only the indices before i for the remaining steps.
  4. 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.

Examples
Input: [[3,34,4,12,5,2],9]
Output: [4,5]
Hints

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`.