这道题实质上就是求一个数组所有的子集,下面用python实现一个,使用的二进制取位来列举所有的子集
test1 = [5, 7, 16, 1, 2]
test2 = [1, 22, 23, 24, 27, 29, 33]
test3 = [1, 22, 23, 25, 26]
test4 = [3, 5, -1, 8, 1, -2, 12]
def getSubArraySum(array,index):
arrayLength = len(array)
sum = 0
for i in range(arrayLength):
if (index>>(arrayLength - i - 1))&1 == 1:
sum += array[i]
return sum
def checkArray(array):
tempArray = array
maxValue = max(tempArray)
del tempArray[tempArray.index(maxValue)]
istrue = False
for i in range(2**len(tempArray)):
if maxValue == getSubArraySum(array,i):
istrue = True
return istrue
return istrue
print checkArray(test1)
print checkArray(test2)
print checkArray(test3)
print checkArray(test4)