如果下次有人遇到麻烦就把答案贴出来。
曲目列表
$listOfTracks = [1,2,3,4,5]
. 这些都是铁轨。
每个对的可用磁道可以添加到数组中(其中索引指对):
$availableTracks = [[1,4],[3,5],[2,3,5],[1,2],[2,4]]
此数组可以可视化为树。第一个包含所有磁道号的组合是一个合适的组合(在上面的例子中,它可以是
1,3,5,2,4
或
4,3,5,1,2
取决于选择哪种算法来遍历树。显然,每种解决方案都可能有一个或两个以上的解决方案,但任务并不是只找到第一个。
遍历树的算法之一是“choose left”,如果可能的话,总是选择最左边的节点(基于前面的例子
$availableTracks = [[1,4],[3,5],[2,3,5],[1,2],[2,4]]
:
Current node [1,4], Select 1, move downwards - $selectedNumbers = [1]
Current node [3,5], Select 3, move downwards - $selectedNumbers = [1,3]
Current node [2,3,5], Select 2, move downwards - $selectedNumbers = [1,3,2]
Current node [1,2], 1 and 2 are only available nodes, both are used, move upwards and continue with different node.
Current node [2,3,5], 2 wasnt suitable, 3 is not suitable (as already used), Select 5, move downwards - $selectedNumbers = [1,3,5].
Current node [1,2], 1 is not suitable (as already used), Select 2, move downwards - `$selectedNumbers = [1,3,5,2]`
Current node [2,4], 2 is not suitable (as already used), Select 4, array has reached the same length as number of pairs, found suitable.
Final list: `$selectedNumbers = [1,3,5,2,4]`