Accepted python solution share


  • 0
    L

    My accepted python solution , used DFS.

    class Solution:
    # @param S, a list of integer
    # @return a list of lists of integer
    def subsets(self, S):
        res=[];
        S=sorted(S,reverse=True);
        res.append([]);
        for i in range(len(S)+1):
            res.extend(self.combineCore(S,i));        
        return res;
    
    
    # @return a list of lists of integers
    def combine(self, n, k):
        return self.combineCore([i for i in range(1,n + 1)],k)
    
    def combineCore(self,vals,k):# this is the key function
        if(k==0):
            return [];
        elif(k == 1):
            vals.reverse()
            return [[i] for i in vals]
        else:
            res = []
            for i in range(len(vals) - 1,-1,-1):
                newVals = vals[0:i]
                prev_combine = self.combineCore(newVals,k - 1)
    
                for comb in prev_combine:
                    comb.append(vals[i])
                    res.append(comb)
            return res;
    

    s=Solution();
    res=s.subsets([4,1,2]);


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.