我必须为算法构建代码。我必须使用我的算法实现以下目标:
我有三个号码,4,6,8。我必须用这些数字中的两个生成总和,然后用这些数字中的三个生成总和,然后用四个等等。当然,在这个例子中可能有重复:4 + 4 + 6
我开始考虑使用“for”循环,因此可以使用两个嵌套的for循环生成其中两个数字的总和。三个嵌套的“for”循环将给出三个数字的总和等等......
我可以通过使用“for”来约束此解决方案,例如直到五个数字的总和,但这不是一般解决方案。
有没有办法或算法或数学方法来做到这一点?
与数学组合学有相似之处。
答案 0 :(得分:1)
答案 1 :(得分:1)
这是subset sum problem的变体,假设你的元素都是小整数,它可以在伪多项式时间内使用动态编程有效地解决。
f(0,i) = true
f(x,i) = false if n < 0
f(x,i) = f(x,i-1) OR f(x-arr[i],i-1)
每个号码x
,f(x,_)=true
就是答案。可以通过避免递归来完成:
table <- int [sum(array)+1][n+1] //2 dimensional table
init table[x][0]=false for each x!=0
init table[0][i]=true for each i
for each x in 1:sum(arr)+1:
for each i in 1:n+1:
if x-arr[i] >= 0:
table[x][i] = table[x][i-1] OR table[x-arr[i]][i-1]
else:
table[x][i] = table[x][i-1]
//done generating table, output answers:
for each x in 1:summ(arr)+1:
if (table[x][n] ==true) print x
这个答案假设子集的大小没有限制 - 如果有,可以通过向表中添加另一个维来完成。
运行时间为O(sum(arr)*n)
答案 2 :(得分:1)
对于任何给定数量的术语,您只需要两个循环。假设您想要n个值的总和。对于任何给定的和,你有n 8 乘以8,n 6 乘以6和n 4 乘以4,n 8 子> + N <子> 6 子> + N <子> 4 子> = N。要生成所有可能的组合,您只需要遍历n 8 和n 6 ,可以从中计算n 4 的值。在Python中:
def findsums(n):
# n8 = [0..n]
for n8 in range(n+1):
#n6 = [0..n-n8]
for n6 in range(n+1-n8):
n4 = n - n8 - n6
# build the string consisting of n terms
s = "+8" * n8 + "+6" * n6 + "+4" * n4
# print, and strip the first '+' character
print( "{0}={1}".format( s[1:], 8*n8+6*n6+4*n4 ) )
findsums(5)