Fast solution to Subset sum

后端 未结 6 1449
不思量自难忘°
不思量自难忘° 2020-11-27 19:09

Consider this way of solving the Subset sum problem:

def subset_summing_to_zero (activities):
  subsets = {0: []}
  for (activity, cost) in activities.iterit         


        
6条回答
  •  忘掉有多难
    2020-11-27 19:55

    I don't know much python, but there is an approach called meet in the middle. Pseudocode:

    Divide activities into two subarrays, A1 and A2
    for both A1 and A2, calculate subsets hashes, H1 and H2, the way You do it in Your question.
    for each (cost, a1) in H1
         if(H2.contains(-cost))
             return a1 + H2[-cost];
    

    This will allow You to double the number of elements of activities You can handle in reasonable time.

提交回复
热议问题