由 F#
let rec comb n l =
match n, l with
| 0, _ -> [[]]
| _, [] -> []
| n, x::xs -> List.map (fun l -> x ::l) (comb (n - 1) xs) @ (comb n xs)
let powersets xs = seq {
for i = 1 to List.length xs do
for x in comb i xs -> x
}
let rec powerset_out xs (acc:int list list) =
if List.isEmpty xs then
System.String.Join(",", seq { for el in acc do yield! el })
|> printfn "%s"
else
let x::xs = xs
for el in powersets x do
powerset_out xs (acc @ [el])
执行示例:
> powerset_out [[1;3;5];[2;4];[1]] [];;
1,2,1
1,4,1
1,2,4,1
3,2,1
3,4,1
3,2,4,1
5,2,1
5,4,1
5,2,4,1
1,3,2,1
1,3,4,1
1,3,2,4,1
1,5,2,1
1,5,4,1
1,5,2,4,1
3,5,2,1
3,5,4,1
3,5,2,4,1
1,3,5,2,1
1,3,5,4,1
1,3,5,2,4,1