英文:
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..
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论