Skip to content

Instantly share code, notes, and snippets.

@lotabout
Created January 3, 2015 09:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lotabout/b7e2774e9b06f5f46b82 to your computer and use it in GitHub Desktop.
Save lotabout/b7e2774e9b06f5f46b82 to your computer and use it in GitHub Desktop.
subset.py
class Solution:
def subsets(self, S):
self.ht = {}
ret = [[]]
s_sorted = sorted(S)
for set_length in range(1, len(S)+1):
ret += self.subset(s_sorted, 0, set_length)
return ret
def subset(self, S, index, l):
if l <= 0:
ret = self.ht[(index,l)] = [[]]
return ret
if len(S)-index == l:
ret = self.ht[(index,l)] = [S[index:]]
return ret
ret = []
for i in range(index, len(S)-l+1):
if i != index and S[i] == S[i-1]:
continue
rest = self.subset(S, i+1, l-1)
for x in rest:
ret.append([S[i]]+x)
self.ht[(index, l)] = ret
return ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment