Engineering platform~15 min2s · 256 MBtarget O(page size × n) time, O(n) spaceclassic twin: lc-78backtracking
A release tool has n feature flags, numbered from 1. A combination is the set of flags that are on, and it may be empty.
There are 2^n combinations, far too many to show at once. The tool lists them in a fixed order and shows one page at a time.
Your team lead says: Decide each flag in turn, skip or take. Skip it before you take it. Stop as soon as the page is full.
Write flag_combinations(n, start, count).
start to start + count - 1 of that list, counting from 0.Input: n = 2, start = 0, count = 4
Output: [[], [2], [1], [1, 2]]Each call decides one flag: it skips it first, then takes it. After both calls it undoes the choice.
| Step | Flag being decided | Chosen so far | Action |
|---|---|---|---|
| 1 | 1 | [] | skip flag 1 first |
| 2 | 2 | [] | skip flag 2 first |
| 3 | none left | [] | a combination: save it |
| 4 | 2 | [2] | take flag 2 |
| 5 | none left | [2] | a combination: save it |
| 6 | 1 | [1] | take flag 1 |
| 7 | 2 | [1] | skip flag 2 first |
| 8 | none left | [1] | a combination: save it |
| 9 | 2 | [1, 2] | take flag 2 |
| 10 | none left | [1, 2] | a combination: save it |
The four combinations, in order, are the four saved rows.
Input: n = 3, start = 2, count = 3
Output: [[2], [2, 3], [1]]The full list for 3 flags has 8 combinations: [], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]. Positions 2 to 4 are the page.
Input: n = 3, start = 6, count = 5
Output: [[1, 2], [1, 2, 3]]Only positions 6 and 7 exist, so the page has 2 combinations.
1 ≤ n ≤ 400 ≤ start ≤ 100,0001 ≤ count ≤ 100With 40 flags there are 1,099,511,627,776 combinations, so the whole list cannot be built. A page needs only start + count of them, at most 100,100. The recursion stops as soon as the page is full.