题目:输入两个长度为n的list A,B,通过交换两个list的值,获得两个新的list,要求这两个list和的差值的绝对值最小:min:abs(sum(A)-sum(B))
在不要求交换后A,B长度相等的条件下,可以使用动态规划的思路求解:
首先计算sum(A + B),求得sum / 2然后,利用0,1背包思路,填充一个最大容量为sum / 2的背包,并获得填包的最好情况,那么所求值即为:min sum(A+B)- 2 * result
动态规划递推式为:
R(n,w)= max(R(n-1, w), R(n-1,w-List(n))+ List(n))
代码如下:
# encoding: GBK
'''
Created on 2014年1月20日
@author: xiaolubambi
'''
def divde_list(a, b):
'''
将两个列表分成 两份 ,使得两份的和的差的绝对值最小
'''
list = a + b
list = sorted(list)
length = len(list)
sum_dive2 = sum(list) / 2
result = [[0 for x in range(sum_dive2 + 1)] for y in range(length)]
for j in range(1, sum_dive2 + 1):
if j >= list[0]:
result[0][j] = list[0]
for i in range(1, length):
for j in range(1, sum_dive2 + 1):
max = 0
if j - list[i] >= 0:
if result[i - 1][j] > result[i - 1][j - list[i]] + list[i]:
max = result[i - 1][j]
else:
max = result[i - 1][j - list[i]] + list[i]
else:
max = result[i - 1][j]
result[i][j] = max
return abs(sum(a + b) - result[i][j] * 2)
if __name__ == '__main__':
a = [1, 2]
b = [1000, 1000]
result = divde_list(a, b)
print result
转载于:https://blog.51cto.com/8415580/1353296