print('sum(l1) - sum(l2):', sum(l1) - sum(l2)) for i in range(5): swp = (0, 0) sub = sub_tmp = sum(l1) - sum(l2) for i, x in enumerate(l1): for j, y in enumerate(l2): # x与y交换之后, SUM(l1) - SUM(l2): # new_sum1 = sum(l1) - x + y # new_sum2 = sum(l2) - y + x # new_sub = new_sum1 - new_sum2 = sum(l1) - sum(l2) - 2x + 2y new_sub = 2 * (x - y) - sub
但我总觉得{i+L[k-1] for i in method2(k-1, i-1)}的时间复杂度是不是没有考虑进去???
原书中的写法, 测试过了, 和递归的结果是一模一样的:
1 2 3 4 5 6
defmethod2_o(N, Heap, L): for k in range(1, 2*N+1): i_max = min(k-1, N-1) for i in reversed(range(0, i_max+1)): for v in Heap[i]: Heap[i+1].add(v+L[k-1])
defmethod3(isOk): # isOk[i][v]: bool(从数组中取i个数, 得到sum为v) for k in range(2*N): for i in reversed(range(1, min(k+1, N)+1)): for v in range(1, int(sum(L)/2+1)): sub = v - L[k] if sub >= 0and isOk[i-1][sub]: isOk[i][v] = True
if __name__ == '__main__': L = [1, 5, 7, 8, 9, 6, 3, 11, 20, 17] N = int(len(L) / 2)
isOk = {x: defaultdict(bool) for x in range(0, N+1)} isOk[0][0] = True method3(isOk)