52ms Python Backtracking solution


  • 1
    Y
    class Solution(object):
        def subsets(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            nums.sort()
            ans,stack,x,n=[[]],[],0,len(nums)
            while True:
                if x<n:
                    stack+=[(x,nums[x])]
                    ans+=[zip(*stack)[1]]
                    x+=1
                elif stack:
                    x=stack.pop()[0]+1
                else:
                    return ans
    

    Is there any alternative without using tuple? The way I can think of is either to maintain two stacks, or still only maintaining one stack of the indices but then we need to get the corresponding nums[x] when appending to ans. Both of them seem to be even slower. Any suggestion is welcome!


  • 0
    W

    a good solution


Log in to reply
 

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