python写算法题:leetcode: 78. Subsets

class Solution(object):
    def _comb(self, lst, k):
        if k==0: return [[]]
        if k==1: 
            return [ [v] for v in lst ]
        ret=[]
        n=len(lst)
        for i in xrange(0, n-k+1):
            #lst[i],lst[0]=lst[0],lst[i]
            #for v in self._comb(lst[1:], k-1):
            #    v.insert(0, lst[0])
            #    ret.append(v)
            #lst[i],lst[0]=lst[0],lst[i]
            
            for v in self._comb(lst[i+1:], k-1):
                v.insert(0, lst[i])
                ret.append(v)
        return ret   
    
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res=[]
        for k in xrange(0,len(nums)+1):
            res.extend(self._comb(nums, k))
        return res

 

你可能感兴趣的:(算法,python)