Friday, June 13, 2014

LeetCode (Python): Subsets

Given a set of distinct integers, S, return all possible subsets.
Note:
  • Elements in a subset must be in non-descending order.
  • The solution set must not contain duplicate subsets.
For example,
If S = [1,2,3], a solution is:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

Solution:

class Solution:
    # @param S, a list of integer
    # @return a list of lists of integer
    def subsets(self, S):
        S.sort()
        solution = []
        self.subsetsRec(S,0, [], solution)
        return solution
    
    def subsetsRec(self, S, index, tempSolution, solution):
        if index == len(S):
            solution.append(list(tempSolution))
        else:
            self.subsetsRec(S,index+1, tempSolution, solution)
            tempSolution.append(S[index])
            self.subsetsRec(S,index+1, tempSolution, solution)
            tempSolution.pop()

No comments :

Post a Comment