Memory efficient power set algorithm

前端 未结 5 1190
鱼传尺愫
鱼传尺愫 2020-12-03 15:42

Trying to calculate all the subsets (power set) of the 9-letter string \'ABCDEFGHI\'.

Using standard recursive methods, my machine hits out of memory (1GB) error bef

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-03 16:25

    I would use divide and conquer for this:

    Set powerSet(Set set) {
      return merge(powerSet(Set leftHalf), powerSet(Set rightHalf));
    }
    
    merge(Set leftHalf, Set rightHalf) {
      return union(leftHalf, rightHalf, allPairwiseCombinations(leftHalf, rightHalf));
    }
    

    That way, you immediately see that the number of solutions is 2^|originalSet| - that's why it is called the "power set". In your case, this would be 2^9, so there should not be an out of memory error on a 1GB machine. I guess you have some error in your algorithm.

提交回复
热议问题