如何生成数字范围的所有组合

Lau*_*llo -3 c python algorithm combinations

我有多个数字范围,例如 [1->5]、[1->3] 和 [1->2]。范围和边界的数量是可变的。

生成所有可能组合的算法(最好是 C 代码)是什么,例如上面的例子:
1 - 1 - 1
1 - 1 - 2
1 - 2 - 1 1 -
2 - 2
1 - 3 - 1
1 - 3 - 2
2 - 1 - 1
...

谢谢。

use*_*500 5

这必须是递归的。python 中的示例代码是:

def variads(lst, lstsofar):
    offset = len(lstsofar)
    outerlen = len(lst)
    innerLst = lst[offset]
    printit = False
    if offset == (outerlen - 1):
        printit = True
    for item in innerLst:
        if printit:
            print (lstsofar + [item])
        else:
            variads(lst, lstsofar + [item])
    return
Run Code Online (Sandbox Code Playgroud)

要调用它,您需要传递一个列表列表:

>>> variads([[1, 2, 3, 4, 5], [1, 2, 3], [1, 2]], [])
[1, 1, 1]
[1, 1, 2]
[1, 2, 1]
[1, 2, 2]
[1, 3, 1]
[1, 3, 2]
[2, 1, 1]
[2, 1, 2]
[2, 2, 1]
[2, 2, 2]
[2, 3, 1]
[2, 3, 2]
[3, 1, 1]
[3, 1, 2]
[3, 2, 1]
[3, 2, 2]
[3, 3, 1]
[3, 3, 2]
[4, 1, 1]
[4, 1, 2]
[4, 2, 1]
[4, 2, 2]
[4, 3, 1]
[4, 3, 2]
[5, 1, 1]
[5, 1, 2]
[5, 2, 1]
[5, 2, 2]
[5, 3, 1]
[5, 3, 2]
Run Code Online (Sandbox Code Playgroud)

上面将处理可变数量的范围。范围在对 的调用中得到扩展variads。如果您只有最大值和最小值,您可以编写一个辅助函数来扩展范围,然后调用variads.

  • 是的,OP仍然需要尝试他自己的代码。 (2认同)