如何在Golang中列出组合可能性

Any idea to make the best code for combination :

with this :

letters := []string{"a", "b", "c", "d"}

to have : a ab ac ad abc abd b bc bcd etc ...

regards and thanks

You are looking for Powerset:

One approach is:

Start with a slice with one empty element, let's call it result:

[[]]

Keep the previous slice, and create a new slice with first element a of you data structure added to you to every element in you original slice.

[[]] <--old; [[a]] <--new

merge them

[[], [a]]

Do the same thing for second element b:

[[], [a]] <--old; [[b], [ab]] <--new

=> [[], [a], [b], [ab]]

for c:

[[], [a], [b], [ab]] <--old; [[c], [ac], [bc], [abc]] <--new

=> [[], [a], [b], [ab], [c], [ac], [bc], [abc]]

and so on..