V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX  ›  breakind  ›  全部回复第 2 页 / 共 2 页
回复总数  27
1  2  
2013-04-04 17:06:41 +08:00
回复了 hzlzh 创建的主题 程序员 [一道有趣的算法题] 各种语言都来试试吧~
错了一点,上面if maxValue == getSubArraySum(array,i):应该为if maxValue == getSubArraySum(tempArray,i):
2013-04-04 17:01:14 +08:00
回复了 hzlzh 创建的主题 程序员 [一道有趣的算法题] 各种语言都来试试吧~
这道题实质上就是求一个数组所有的子集,下面用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)
1  2  
关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1006 人在线   最高记录 6543   ·     Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 17ms · UTC 20:06 · PVG 04:06 · LAX 13:06 · JFK 16:06
Developed with CodeLauncher
♥ Do have faith in what you're doing.