Engineering platform~25 min2s · 256 MBtarget O(n!) worst case, far less with pruning time, O(n) spaceclassic twin: lc-46backtracking
A build system has n stages, numbered from 0, and each stage must run exactly once. Stage b can run straight after stage a only when the system lists the hand-off a to b, because the output of a must be readable by b.
The team wants to know how many different orders of all n stages are possible. Two orders are different when some position holds a different stage.
Write count_stage_orders(stages, handoffs).
stages is the number of stages, numbered 0 to stages - 1.handoffs[i] is [a, b]: stage b may run directly after stage a. The reverse, b then a, is allowed only if it is listed too.Input: stages = 4, handoffs = [[0,1],[1,2],[2,3],[0,2],[1,3],[3,0],[2,1]]
Output: 8The solution fills the positions one at a time. At each position it tries every unused stage that may follow the last one. It takes a stage back when it has counted the orders that continue from it.
| First stage | Orders that follow |
|---|---|
| 0 | 0,1,2,3 and 0,2,1,3 |
| 1 | 1,2,3,0 and 1,3,0,2 |
| 2 | 2,1,3,0 and 2,3,0,1 |
| 3 | 3,0,1,2 and 3,0,2,1 |
Each first stage has 2 orders, so the answer is 8.
Input: stages = 3, handoffs = [[0,1],[1,2],[2,0]]
Output: 3Each stage can only be followed by one other stage. The orders are 0,1,2, 1,2,0 and 2,0,1.
Input: stages = 3, handoffs = [[0,1]]
Output: 0Stage 2 has no allowed hand-off to or from any stage, so no order can include it next to a neighbour. The answer is 0.
1 ≤ stages ≤ 100 ≤ len(handoffs) ≤ 90, and every hand-off is [a, b] with 0 ≤ a, b < stages. A hand-off can be listed more than onceTen stages have 10 factorial orders, which is 3,628,800. Building every order and checking it costs about 10 times that many steps. The search checks each hand-off as it places a stage, so an order that breaks a rule is never built past the break.