Elegant Python Solution (4 lines)

  • 0

    We iterate through numbers one at a time, and combine previously seen results with our number to add new results

    To prevent duplicates, we store the results in a set. To do this we need to store the results as tuples (immutable lists), which we cast back to lists before returning. Note the interesting syntax needed to create a tuple of length 1

    def subsets(self, nums):
        res = set([()])
        for num in sorted(nums):
            res.update([item+(num, ) for item in res if item+(num, ) not in res])
        return [list(item) for item in res]

Log in to reply

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