It is clean python code.


  • 0
    W

    same idea as most of you doing iterations.

    get subset from current result add new element and append to result.

    note that result set is change in each loop.

    class Solution(object):
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        result = [[]]
        nums.sort()
        for i in range(len(nums)):
            for j in range(len(result)):
                subset = result[j] + [nums[i]]
                result.append(subset)
        return result
    

    if we are doing backtracking

    class Solution(object):
    def backtrack(self, candidates, val, res, start):
        res.append(val)
        for i in range(start, len(candidates)):
            self.backtrack(candidates, val + [candidates[i]], res, i + 1)
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res = []
        nums.sort()
        self.backtrack(nums, [], res, 0)
        return res

Log in to reply
 

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