Leetcode: Permutations

Question

Given a collection of numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].

Show Tags
Show Similar Problems

Solution 1

Get idea from here.

recursion method

class Solution(object):
    def permute(self, nums):
        """ :type nums: List[int] :rtype: List[List[int]] """

        res,cur = [], []
        self.helper( nums, cur, res)
        return res

    def helper(self, lst, cur, res):
        if lst==[]:
            res.append(cur)
            return 

        for ind,elem in enumerate(lst):
            temp = lst[:]
            del temp[ind]
            self.helper( temp, cur+[elem], res)

Solution 2

iteration method

class Solution(object):
    def permute(self, nums):
        """ :type nums: List[int] :rtype: List[List[int]] """

        if len(nums)==0:
            return []

        res = [[nums[0]]]

        for ind in range(1,len(nums)):
            newres = []
            for resind in range(len(res)):
                cur = res[resind]
                for curind in range(len(cur)+1):
                    newitem = cur[:curind] + [nums[ind]] + cur[curind:]
                    newres.append(newitem)

            res = newres

        return res      

你可能感兴趣的:(Leetcode: Permutations)