Tom*_*cek 19
你也可以写这样的东西:
let rec permutations list taken =
seq { if Set.count taken = List.length list then yield [] else
for l in list do
if not (Set.contains l taken) then
for perm in permutations list (Set.add l taken) do
yield l::perm }
Run Code Online (Sandbox Code Playgroud)
'list'参数包含您要置换的所有数字,'taken'是包含已使用数字的集合.所有数字全部采用时,该函数返回空列表.否则,它迭代所有仍然可用的数字,获得剩余数字的所有可能排列(递归地使用'permutations')并在返回(l :: perm)之前将当前数字附加到每个数字.
要运行它,你会给它一个空集,因为在开头没有使用数字:
permutations [1;2;3] Set.empty;;
Run Code Online (Sandbox Code Playgroud)
Joh*_*bom 13
我喜欢这个实现(但不记得它的来源):
let rec insertions x = function
| [] -> [[x]]
| (y :: ys) as l -> (x::l)::(List.map (fun x -> y::x) (insertions x ys))
let rec permutations = function
| [] -> seq [ [] ]
| x :: xs -> Seq.concat (Seq.map (insertions x) (permutations xs))
Run Code Online (Sandbox Code Playgroud)