5 line python code with easy explanation


  • 3
    class Solution(object):
        def subsets(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            res = [[]]
            for i in range(len(nums)):
                k = nums[i]
                res += map(lambda x:x+[k],res)
            return res
    

    let nums = [1,2,3]
    First initialize res as empty list [[]], then pick the first element from nums, that is 1. Then append 1 to all subsets in res, also append the original res to update current res, so res becomes[[],[1]], then pick 2 from nums, res becomes[[],[1],[2],[1,2]]. Finally pick 3 from nums, res becomes [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]. This can be done easily by lambda functions.


  • 0
    S

    Excellent solution.


Log in to reply
 

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