本文共 1625 字,大约阅读时间需要 5 分钟。
??????????????????????????????????????
????????????????????????????????????????????
?????
????????????
?????
def count_subset_pairs(collection): total = sum(collection) if total % 2 != 0: return 0 n = len(collection) mid = n // 2 left = collection[:mid] right = collection[mid:] from collections import defaultdict left_counts = defaultdict(int) for subset in generate_subsets(left): left_counts[sum(subset)] += 1 right_counts = defaultdict(int) for subset in generate_subsets(right): right_counts[sum(subset)] += 1 target = total // 2 count = 0 for s in left_counts: if (target - s) in right_counts: count += left_counts[s] * right_counts[target - s] return countdef generate_subsets(arr): n = len(arr) subsets = [] for i in range(1, 1 << n): subset = [] for j in range(n): if (i >> j) & 1: subset.append(arr[j]) subsets.append(subset) return subsets# ????test_collection = [1, 2, 3, 4, 5, 6]print(count_subset_pairs(test_collection))
??????
?????
?????
generate_subsets??????????????????????????????
???
??????????????????????????????????????????????n??????????
转载地址:http://ebwo.baihongyu.com/