A python non-recursive method


  • 0
    class Solution(object):
        def __init__(self):
            self.ret = []   
    
        def permutation_nr(self, i, nums, res):
            stack = []
            j = 0
            while j < len(nums) or len(stack) > 0:
                if j == len(nums) and len(stack) == 0:
                    break
                if nums[j] not in res:
                    res.append(nums[j])
                    if len(res) == len(nums):
                        self.ret.append(res[:])
                        res.pop()
                        res.pop()
                        j = stack.pop() + 1
                    else:
                        stack.append(j)
                        j = 0
                else:
                    j += 1
    
                while j == len(nums) and len(stack) > 0:
                    j = stack.pop() + 1
                    res.pop()
    
        def permute(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            if nums is None or len(nums) == 1:
                return [nums]
            res = []
            self.permutation_nr(0, nums, res)
            return self.ret

Log in to reply
 

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