输入一个任意长度的整形数组,把它分成两个数组,要求使得这两个数组各自的和相同,如果不能相同,做到差距(各自之和的差的绝对值)最小,如果有多个解决方案,返回任意一个就行
import copy
def incomplete_solution(arr):
total = sum(arr)
half = total/2
possibleSolution = {0: []}
for i in arr:
possibleSum = possibleSolution.keys()
for k in list(possibleSum):
now = i + k
if (now not in possibleSum):
valueList = possibleSolution[k]
nowList = copy.copy(valueList)
nowList.append(i)
possibleSolution[now] = nowList
if (now == half):
return nowList
possibleSolution = {0: []}
for i in arr:
possibleSum = possibleSolution.keys()
for k in list(possibleSum):
now = i + k
if (now not in possibleSum):
valueList = possibleSolution[k]
nowList = copy.copy(valueList)
nowList.append(i)
possibleSolution[now] = nowList
if (now > half):
return nowList
if __name__ == '__main__':
arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
n = incomplete_solution(arr)
for i in n:
arr.remove(i)
print(n)
print(arr)