子集和数问题

def sum_of_sub(s,k,r):
    global M,w,x
    x[k]=1
    if s+w[k]== M:
        print(x[1:k+1])
    elif s+w[k]+w[k+1]<=M:
        sum_of_sub(s+w[k],k+1,r-w[k])
    if s+r-w[k]>=M and s+w[k+1]<=M:
        x[k]=0
        sum_of_sub(s,k+1,r-w[k])
        
#test
M=30
w=[0,5,10,12,13,15,18] #w[0]不用
n=len(w)
x=[0 for i in range(n)]
r=0
for i in w:
    r+=i
sum_of_sub(0,1,r)

你可能感兴趣的:(编程练习)