def knapSack(A,L,R,K,N,Sum):
if(K==0):
if((L>=Sum)or(R<=Sum)):
return 1
else:
return 0
if((N==0)and(K!=0)):
return 0
else:
return knapSack(A,L,R,K,N-1,Sum)+knapSack(A,L,R,K-1,N-1,Sum:=Sum+A[N-1])
A = [2,4,10,25]
K = 2
L = 3
R = 13
Sum=0
n = len(A)
print(knapSack(A,L,R,K,n,Sum))
这段代码的输出是: 4
解释:
25+10 =35
25+4 = 29
25+2 = 27
10+4 = 14
这些和满足给定条件 if((L>=Sum)or(R<=Sum )) 其中 L=3 R=13
K 是子集的大小。这里,K = 2
当 K = 3
A = [2,4,10,25]
K = 3
L = 3
R = 13
Sum = 0
n = len(A)
print(knapSack(A,L,R,K,n,Sum))
当 K = 3 时,此代码的输出为: 4
解释:
4+10+25 = 39
2+4+25 = 31
2+10+25 = 37
2+4+10 = 16
这些和满足给定条件 if( (L>=Sum)or(R<=Sum)) where L=3 R=13
有没有办法在动态规划或任何其他更好的方法中解决这个问题?