我想创建所有可能的size(N)数组的组合,假设元素可以是[-1,0,1],但是它只允许最多有2个元素[-1,1],而所有其他元素都应该是0。
递归方法可以满足N<1000的要求,但我正在寻找有效的(内存和计算)方法来生成直到N=10000。
对于N=6的递归情况和结果的尝试如下:
def generate_combinations(N):
elements = [-1, 0, 1]
combinations = []
generate_combinations_recursive(elements, N, [], 0, 0, combinations)
return combinations
def generate_combinations_recursive(elements, repetitions, current_combination, num_nonzero, index, combinations):
if index == repetitions:
combinations.append(tuple(current_combination))
return
for element in elements:
if element != 0:
if num_nonzero < 2:
generate_combinations_recursive(elements, repetitions, current_combination + [element], num_nonzero + 1,
index + 1, combinations)
else:
generate_combinations_recursive(elements, repetitions, current_combination + [element], num_nonzero,
index + 1, combinations)
combinations = generate_combinations(N=6)
结果
[(-1, -1, 0, 0, 0, 0),
(-1, 0, -1, 0, 0, 0),
(-1, 0, 0, -1, 0, 0),
(-1, 0, 0, 0, -1, 0),
(-1, 0, 0, 0, 0, -1),
(-1, 0, 0, 0, 0, 0),
(-1, 0, 0, 0, 0, 1),
(-1, 0, 0, 0, 1, 0),
(-1, 0, 0, 1, 0, 0),
(-1, 0, 1, 0, 0, 0),
(-1, 1, 0, 0, 0, 0),
(0, -1, -1, 0, 0, 0),
(0, -1, 0, -1, 0, 0),
(0, -1, 0, 0, -1, 0),
(0, -1, 0, 0, 0, -1),
(0, -1, 0, 0, 0, 0),
(0, -1, 0, 0, 0, 1),
(0, -1, 0, 0, 1, 0),
(0, -1, 0, 1, 0, 0),
(0, -1, 1, 0, 0, 0),
(0, 0, -1, -1, 0, 0),
(0, 0, -1, 0, -1, 0),
(0, 0, -1, 0, 0, -1),
(0, 0, -1, 0, 0, 0),
(0, 0, -1, 0, 0, 1),
(0, 0, -1, 0, 1, 0),
(0, 0, -1, 1, 0, 0),
(0, 0, 0, -1, -1, 0),
(0, 0, 0, -1, 0, -1),
(0, 0, 0, -1, 0, 0),
(0, 0, 0, -1, 0, 1),
(0, 0, 0, -1, 1, 0),
(0, 0, 0, 0, -1, -1),
(0, 0, 0, 0, -1, 0),
(0, 0, 0, 0, -1, 1),
(0, 0, 0, 0, 0, -1),
(0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 1),
(0, 0, 0, 0, 1, -1),
(0, 0, 0, 0, 1, 0),
(0, 0, 0, 0, 1, 1),
(0, 0, 0, 1, -1, 0),
(0, 0, 0, 1, 0, -1),
(0, 0, 0, 1, 0, 0),
(0, 0, 0, 1, 0, 1),
(0, 0, 0, 1, 1, 0),
(0, 0, 1, -1, 0, 0),
(0, 0, 1, 0, -1, 0),
(0, 0, 1, 0, 0, -1),
(0, 0, 1, 0, 0, 0),
(0, 0, 1, 0, 0, 1),
(0, 0, 1, 0, 1, 0),
(0, 0, 1, 1, 0, 0),
(0, 1, -1, 0, 0, 0),
(0, 1, 0, -1, 0, 0),
(0, 1, 0, 0, -1, 0),
(0, 1, 0, 0, 0, -1),
(0, 1, 0, 0, 0, 0),
(0, 1, 0, 0, 0, 1),
(0, 1, 0, 0, 1, 0),
(0, 1, 0, 1, 0, 0),
(0, 1, 1, 0, 0, 0),
(1, -1, 0, 0, 0, 0),
(1, 0, -1, 0, 0, 0),
(1, 0, 0, -1, 0, 0),
(1, 0, 0, 0, -1, 0),
(1, 0, 0, 0, 0, -1),
(1, 0, 0, 0, 0, 0),
(1, 0, 0, 0, 0, 1),
(1, 0, 0, 0, 1, 0),
(1, 0, 0, 1, 0, 0),
(1, 0, 1, 0, 0, 0),
(1, 1, 0, 0, 0, 0)]
3条答案
按热度按时间f45qwnt81#
像这样的东西应该可以。只需立即处理输出,数组将在下一次迭代中修改:
似乎总是有
2 * N^2 + 1
结果。8xiog9wr2#
在this answer之后,您可以使用
sympy
函数sympy.utilities.iterables.multiset_permutations
并从中创建生成器函数。wvmv3b1j3#
不需要图书馆。没有重复。这也可以用于您的问题的许多微小变化。
这是可行的,并产生了正确的结果,但你会得到深度递归。
同样的事情没有递归。
当我将最后一个修改为只计算解决方案并使用pypy时,它在2分钟内运行了
n = 1000
。它的运行为10000以及,但这可能需要一天的时间才能完成。