【发布时间】:2017-03-06 23:20:13
【问题描述】:
我正在研究平衡分区问题here 和here (problem 7)。
问题基本上要求将给定的数字数组划分为 2 个子集(S1 和 S2),以便数字总和之间的绝对差为 S1 和 S2 |sum(S1) - sum(S2)| 需要最小。我不明白的一件事是为什么没有人建议贪婪的方法:
def balanced_partition(lst):
idx = 0
S1 = 0
S2 = 0
result_partition=[None]*len(lst)
while idx < len(lst):
new_S1 = S1 + lst[idx]
new_S2 = S2 + lst[idx]
if abs(new_S1 - S2) < abs(new_S2 - S1):
result_partition[idx] = 1
S1 = new_S1
else:
result_partition[idx] = 2
S2 = new_S2
idx += 1
print("final sums s1 = {S1} and s2 = {S2} ".format(S1=S1, S2=S2))
return result_partition
我的方法有什么问题?它似乎通过了我能想到的所有测试用例。
【问题讨论】:
-
“它似乎通过了大部分测试用例”。所以它失败了一些测试用例?这不能回答你的问题吗?
-
对于大多数测试用例,我的意思是我找不到任何反对贪婪方法的论据,我自己也无法(提出)/找到负面测试用例。编辑了我的问题。
-
您是如何搜索负面测试用例的?几乎每个排序列表都是您的最佳方法的反例(例如:[1,2,3])。
-
simple google search 没有帮助,我并没有真正想到排序大小写。
-
我不认为你可以尝试太多——大多数未排序的列表也是反例。即使您只考虑长度为 3 的列表,[random.randrange(1000) for _ in xrange(3)] 大约是 1/3 的反例。
标签: algorithm dynamic-programming greedy