Monitoring~20 min2s · 256 MBtarget O((start + count) × n) time, O(n) spaceclassic twin: lc-46backtracking
A monitoring pipeline has n stages, each with its own id. The stages can run in any order, and the cost of a run depends on the order.
There are n! orderings. The team reviews them in a fixed order, a page at a time.
Your team lead says: Fill the positions one by one. At each position, try every unused stage in input order. Stop as soon as the page is full.
Write pipeline_orderings(stages, start, count).
stages are all different.start to start + count - 1 of that list, counting from 0, each as a list of ids.Input: stages = [5, 8, 2], start = 0, count = 6
Output: [[5, 8, 2], [5, 2, 8], [8, 5, 2], [8, 2, 5], [2, 5, 8], [2, 8, 5]]Each call fills the next position. It tries every unused stage in input order, explores, and then undoes the choice.
| Step | Order so far | Action |
|---|---|---|
| 1 | [5] | choose stage 5 |
| 2 | [5, 8] | choose stage 8 |
| 3 | [5, 8, 2] | choose stage 2 |
| 4 | [5, 8, 2] | an ordering: save it |
| 5 | [5, 2] | choose stage 2 |
| 6 | [5, 2, 8] | choose stage 8 |
| 7 | [5, 2, 8] | an ordering: save it |
| 8 | [8] | choose stage 8 |
| 9 | [8, 5] | choose stage 5 |
| 10 | [8, 5, 2] | choose stage 2 |
| 11 | [8, 5, 2] | an ordering: save it |
| 12 | [8, 2] | choose stage 2 |
| ... | ... | the remaining 3 orderings follow in the same way |
The six orderings, in order, are [5, 8, 2], [5, 2, 8], [8, 5, 2], [8, 2, 5], [2, 5, 8], [2, 8, 5].
Input: stages = [3, 1, 4, 2], start = 10, count = 5
Output: [[1, 2, 3, 4], [1, 2, 4, 3], [4, 3, 1, 2], [4, 3, 2, 1], [4, 1, 3, 2]]Four stages have 24 orderings. Positions 10 to 14 are the page.
Input: stages = [7, 9], start = 1, count = 9
Output: [[9, 7]]Two stages have 2 orderings. Only position 1 is left, so the page has 1 ordering.
1 ≤ stages.length ≤ 12, and all ids are different1 ≤ stages[i] ≤ 1,000,0000 ≤ start ≤ 100,0001 ≤ count ≤ 100With 12 stages there are 479,001,600 orderings, and 10 stages already have 3,628,800. A page needs only start + count of them, at most 100,100. The recursion stops as soon as the page is full.