如何通过一组n
个数字中的替换和订单事项生成所有排列(订单事项),每个组合中包含m
个元素?
我不想使用更多内存,只要我生成一个组合,我就想使用它。
答案 0 :(得分:1)
首先,请注意,如果允许订单重要和替换,您基本上有n
选项来选择每个元素(m
) - 并且您拥有的选择量保持不变。
这意味着您有n*n*...*n = n^m
种可能的组合。
要生成它们,您可以使用递归:
Python代码:(如果您不了解python,只需将其作为伪代码阅读,它就非常清楚了。)
def generateAll(numbers, m, currentPermutation=[]):
if m == 0:
doSomething(currentPermutation)
return
for x in numbers:
currentPermutation.append(x)
generateAll(numbers, m-1, currentPermutation)
currentPermutation.pop()
例如,如果我们定义
def doSomething(l):
print str(l)
并运行
generateAll([1,2,3], 4)
输出将打印所有带有重新定位的组合,其中订单很重要,大小为4 [1,2,3]:
[1, 1, 1, 1]
[1, 1, 1, 2]
[1, 1, 1, 3]
[1, 1, 2, 1]
[1, 1, 2, 2]
[1, 1, 2, 3]
[1, 1, 3, 1]
[1, 1, 3, 2]
[1, 1, 3, 3]
[1, 2, 1, 1]
[1, 2, 1, 2]
[1, 2, 1, 3]
[1, 2, 2, 1]
[1, 2, 2, 2]
[1, 2, 2, 3]
[1, 2, 3, 1]
[1, 2, 3, 2]
[1, 2, 3, 3]
[1, 3, 1, 1]
[1, 3, 1, 2]
[1, 3, 1, 3]
[1, 3, 2, 1]
[1, 3, 2, 2]
[1, 3, 2, 3]
[1, 3, 3, 1]
[1, 3, 3, 2]
[1, 3, 3, 3]
[2, 1, 1, 1]
[2, 1, 1, 2]
[2, 1, 1, 3]
[2, 1, 2, 1]
[2, 1, 2, 2]
[2, 1, 2, 3]
[2, 1, 3, 1]
[2, 1, 3, 2]
[2, 1, 3, 3]
[2, 2, 1, 1]
[2, 2, 1, 2]
[2, 2, 1, 3]
[2, 2, 2, 1]
[2, 2, 2, 2]
[2, 2, 2, 3]
[2, 2, 3, 1]
[2, 2, 3, 2]
[2, 2, 3, 3]
[2, 3, 1, 1]
[2, 3, 1, 2]
[2, 3, 1,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