How to list combination possibility in golang

huangapple go评论76阅读模式
英文:

How to list combination possibility in golang

问题

有没有关于如何编写最佳代码来实现以下组合的想法:

给定:

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

要得到:a ab ac ad abc abd b bc bcd 等等...

谢谢!

英文:

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

答案1

得分: 2

你正在寻找 Powerset(幂集)算法:

一种方法是:

从一个只包含一个空元素的切片开始,我们称之为结果:

[[]]

保留上一个切片,并创建一个新的切片,将你的数据结构的第一个元素 a 添加到原始切片的每个元素中。

[[]] <-- 旧的;[[a]] <-- 新的

合并它们:

[[], [a]]

对于第二个元素 b,执行相同的操作:

[[], [a]] <-- 旧的;[[b], [ab]] <-- 新的

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

对于 c

[[], [a], [b], [ab]] <-- 旧的;[[c], [ac], [bc], [abc]] <-- 新的

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

依此类推...

英文:

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..

huangapple
  • 本文由 发表于 2017年2月23日 07:11:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/42404058.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定