Python 2-line solution using itertools to generate a powerset

  • 0
    class Solution(object):
        def subsets(self, nums):
            :type nums: List[int]
            :rtype: List[List[int]]
            from itertools import chain, combinations
            return list(chain.from_iterable(combinations(nums, r) for r in range(len(nums) + 1)))

    I make use of combinations to generate all combinations from selecting 0 (empty list) to all items from nums. Chain.from_iterable then puts all of the combinations results into a single iterable. Finally, list() to format it in the format needed to match desired output.

Log in to reply

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