我迅速编写了一些代码来执行此操作。但是,我没有将给定列表的所有可能组合分开,因为我不确定它是否真的需要,但如果需要,它应该很容易添加。
无论如何,少量代码运行得很好,但是,正如 CodeByMoonlight 已经提到的那样,可能性的数量变得非常快,因此运行时间相应增加。
无论如何,这是python代码:
import time
def separate(toseparate):
"Find every possible way to separate a given list."
#The list of every possibility
possibilities = []
n = len(toseparate)
#We can distribute n-1 separations in the given list, so iterate from 0 to n
for i in xrange(n):
#Create a copy of the list to avoid modifying the already existing list
copy = list(toseparate)
#A boolean list indicating where a separator is put. 'True' indicates a separator
#and 'False', of course, no separator.
#The list will contain i separators, the rest is filled with 'False'
separators = [True]*i + [False]*(n-i-1)
for j in xrange(len(separators)):
#We insert the separators into our given list. The separators have to
#be between two elements. The index between two elements is always
#2*[index of the left element]+1.
copy.insert(2*j+1, separators[j])
#The first possibility is, of course, the one we just created
possibilities.append(list(copy))
#The following is a modification of the QuickPerm algorithm, which finds
#all possible permutations of a given list. It was modified to only permutate
#the spaces between two elements, so it finds every possibility to insert n
#separators in the given list.
m = len(separators)
hi, lo = 1, 0
p = [0]*m
while hi < m:
if p[hi] < hi:
lo = (hi%2)*p[hi]
copy[2*lo+1], copy[2*hi+1] = copy[2*hi+1], copy[2*lo+1]
#Since the items are non-unique, some possibilities will show up more than once, so we
#avoid this by checking first.
if not copy in possibilities:
possibilities.append(list(copy))
p[hi] += 1
hi = 1
else:
p[hi] = 0
hi += 1
return possibilities
t1 = time.time()
separations = separate([2, 3, 3, 5])
print time.time()-t1
sepmap = {True:"|", False:""}
for a in separations:
for b in a:
if sepmap.has_key(b):
print sepmap[b],
else:
print b,
print "\n",
它基于 QuickPerm 算法,您可以在此处阅读更多信息:QuickPerm
基本上,我的代码生成一个包含 n 个分隔符的列表,将它们插入给定列表中,然后在列表中找到所有可能的分隔符排列。
因此,如果我们使用您的示例,我们将得到:
2 3 3 5
2 | 3 3 5
2 3 | 3 5
2 3 3 | 5
2 | 3 | 3 5
2 3 | 3 | 5
2 | 3 3 | 5
2 | 3 | 3 | 5
在 0.000154972076416 秒内。
但是,我通读了您正在做的问题的问题描述,我看到了您是如何尝试解决这个问题的,但是看到运行时间增加的速度有多快,我认为它不会像您期望的那样快速工作。请记住,Project Euler 的问题应该在大约一分钟内解决。