【问题标题】:A full combination of some arrays一些数组的完整组合
【发布时间】:2021-07-15 17:29:29
【问题描述】:

如果我有一些长度未知的数组,如何获得它们的完整组合?方法越多越好! 例如:

lista, listb, listc = ['abc', 'asd'], ['zxc', 'rty', 'fgh'], ['uio']

结果

result = ['abczxcuio', 'abcrtyuio', ···]

也许这个问题可以递归解决,对吧?但是我这么菜鸟,一直没能理解递归的本质。

非常感谢:)

【问题讨论】:

  • 这个问题可能有点宽泛,但你在递归的正确轨道上。想想“第一个列表的每个元素,与其余列表的每个组合相结合。”
  • 这能回答你的问题吗? Generating Combinations in python
  • @Manuel 这个链接很有用!感谢您的回复!

标签: algorithm recursion


【解决方案1】:

你用嵌套循环来做:

for a in lista :
    for b in listb :
        for c in listc :
            add (a + b + c) to output

如果你不知道这些数组中有多少给你,在一个列表中,那么你将需要使用递归来有效地构建这个嵌套循环结构。

在模式匹配等式伪代码中,

combine( [lista, ...lists] )  =  for a in lista: go( [a], lists )

go( abc, [listd, ...lists] )  =  for d in listd: go( abc+[d], lists)

go( abcd, [] )  =  ....handle the combination abcd....

处理边缘情况,使其发挥作用。

这可以通过索引/指针杂耍来实现,以使其高效,在类 C 语言中,无需分配过多的额外内存(当然输出除外)。

这种方法称为

创建一个临时结构来产生结果会非常快速地增长——组合的数量实际上是指数级的。使用这种方法,您只需在最嵌套的循环内完成一次工作。

附:更多链接探索:1234567...

【讨论】:

  • 你的伪代码看起来和我一开始的想法很相似,但是我的编码能力很差。你能花几分钟用一种通用的编程语言来实现它吗?谢谢!
  • 不确定“常见”,但请参阅here,特别是this(其中也有一些链接)和this。和this。还有更多...
  • some here,例如this。还有this.
  • you're welcome. 顺便说一句,您接受的答案是通过创建临时结构来工作的,该结构将非常快速地增长——组合的数量实际上是指数级的。使用我的方法,您只需在最嵌套的循环内完成一次工作。
【解决方案2】:

考虑递归方法很简单:

如果只有一个列表,则返回它。否则,生成最后两个列表的所有组合,删除它们,将组合添加到列表中并重复 n-1 列表,其中 n 是列表的初始数量。 示例:

def generate(lists):
    # lists is a 2D list i.e list of lists
    if len(lists)<2:
        return lists    #base case
    list1, list2 = lists[-2], lists[-1]
    lists.pop()
    lists.pop()
    combinations = []
    for i in list1:
        for j in list2:
            combinations.append(i+j)
    lists.append(combinations)
    return generate(lists)

lists = [['abc', 'asd'], ['zxc', 'rty', 'fgh'], ['uio']]
print(generate(lists))
# prints [['abczxcuio', 'abcrtyuio', 'abcfghuio', 'asdzxcuio', 'asdrtyuio', 'asdfghuio']]

【讨论】:

  • 最后两个合二为一,对吧?很有意思。感谢您的回复!
猜你喜欢
  • 2020-11-22
  • 2019-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-03
  • 1970-01-01
  • 2021-06-01
相关资源
最近更新 更多