← DiffPush

Combination Sum 1

Standard Bar Recursion · Subsequences Pattern O(N^target) · O(target) recursion depth beyond the output

Vending Combinations from Unlimited Coin Bins

A parts dispenser stocks bins of distinct bolt sizes, and maintenance orders can request any total length — with a bin reused as many times as needed. The dispatcher builds each order by walking the sorted bins: either draw from the current bin again (target shrinks, bin stays) or move on to the next bin for good. Every branch whose remaining target hits exactly zero is a valid fulfilment plan.

Input: An array candidates of distinct positive integers and an integer target.

Output: Every combination summing to target, sorted lexicographically by the verifier.

Constraints

Examples

Example 1

Input: {"candidates":[2,3,6,7],"target":7}
Output: [[2,2,3],[7]]
Two plans: one bin of 7, or 2 drawn twice plus a 3.

Example 2

Input: {"candidates":[2,3,5],"target":8}
Output: [[2,2,2,2],[2,3,3],[3,5]]
Unlimited reuse means 2 can anchor a four-draw plan as well as pair with 3s.

Solve this in your browser →

Also on LeetCode ↗