Parcel-delivery app~20 min2s · 256 MBtarget O((start + count) × n) time, O(n) spaceclassic twin: lc-47backtracking
A delivery planner has n stops, and each stop has a kind: a number for a pickup, a drop-off or a service. Several stops can share a kind.
A route is an ordering of the kinds. Two routes that list the same kinds in the same order are the same route, whichever stops were used.
Your team lead says: Sort the stops first. At each position, skip a stop equal to the one before it when that one is still unused. List a page at a time.
Write distinct_orderings(stops, start, count).
stops from the smallest.start to start + count - 1 of that list, counting from 0. If the list ends first, return the orderings that exist.Input: stops = [1, 2, 1], start = 0, count = 100
Output: [[1, 1, 2], [1, 2, 1], [2, 1, 1]]The sorted stops are [1, 1, 2]. Each call tries every unused stop, but it skips the second 1 while the first 1 is unused.
| Step | Order so far | Action |
|---|---|---|
| 1 | [1] | choose 1 |
| 2 | [1, 1] | choose 1 |
| 3 | [1, 1, 2] | choose 2 |
| 4 | [1, 1, 2] | an ordering: save it |
| 5 | [1, 2] | choose 2 |
| 6 | [1, 2, 1] | choose 1 |
| 7 | [1, 2, 1] | an ordering: save it |
| 8 | [] | skip the second 1: the first is unused |
| 9 | [2] | choose 2 |
| 10 | [2, 1] | choose 1 |
| 11 | [2, 1, 1] | choose 1 |
| 12 | [2, 1, 1] | an ordering: save it |
| 13 | [2] | skip the second 1: the first is unused |
The stops have 6 orderings with repeats, but only 3 different ones.
Input: stops = [3, 3, 5, 5], start = 2, count = 3
Output: [[3, 5, 5, 3], [5, 3, 3, 5], [5, 3, 5, 3]]Four stops in two pairs have 6 different orderings. Positions 2 to 4 are the page.
Input: stops = [7, 7], start = 0, count = 5
Output: [[7, 7]]Two equal stops have one ordering.
1 ≤ stops.length ≤ 121 ≤ stops[i] ≤ 1,000, and kinds may repeat0 ≤ start ≤ 100,0001 ≤ count ≤ 100Twelve stops of 6 kinds, two of each, have 7,484,400 different orderings, where 12 different stops have 479,001,600. A page needs only start + count of them, so the recursion can stop early.