Online store~20 min2s · 256 MBtarget O((start + count) × n) time, O(n) spaceclassic twin: lc-90backtracking
A shop app builds bundles from a cart. Each item is a product id, and the same id can appear several times, one for each unit in the cart.
A bundle is a set of items taken from the cart, and it may be empty. Two bundles with the same ids are the same bundle, whichever units were taken.
Your team lead says: Sort the cart first. At each step, skip an item that equals the one you tried last. List a page at a time.
Write distinct_bundles(items, start, count).
items from the smallest. Write each bundle as its ids in increasing order.start to start + count - 1 of that list, counting from 0.Input: items = [2, 1, 2], start = 0, count = 100
Output: [[], [1], [1, 2], [1, 2, 2], [2], [2, 2]]The sorted cart is [1, 2, 2]. Each call saves its bundle, then tries every later item. It skips an item that equals the one tried before it at the same step.
| Step | Bundle so far | Action |
|---|---|---|
| 1 | [] | an answer: save it |
| 2 | [1] | an answer: save it |
| 3 | [1, 2] | an answer: save it |
| 4 | [1, 2, 2] | an answer: save it |
| 5 | [1] | skip the 2 at position 2: equal to the one before |
| 6 | [2] | an answer: save it |
| 7 | [2, 2] | an answer: save it |
| 8 | [] | skip the 2 at position 2: equal to the one before |
The cart has 8 subsets, but only 6 different bundles.
Input: items = [3, 3, 3, 5], start = 2, count = 4
Output: [[3, 3], [3, 3, 3], [3, 3, 3, 5], [3, 3, 5]]Three units of 3 and one 5 give 8 different bundles. Positions 2 to 5 are the page.
Input: items = [7], start = 1, count = 3
Output: [[7]]One item gives 2 bundles: the empty one and [7]. Only position 1 is left.
1 ≤ items.length ≤ 401 ≤ items[i] ≤ 1,000, and ids may repeat0 ≤ start ≤ 100,0001 ≤ count ≤ 100With 40 different ids there are 1,099,511,627,776 bundles. With 20 units of one id and 20 of another there are only 441. A page needs only start + count of them, so the recursion can stop early.