leetcode: Recursive 46.47 Permutations I II

Topic 46 Permutations I

Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]

Output:

[

 [1,2,3],
        [1,3,2],
        [2,1,3],
        [2,3,1],
        [3,1,2],
        [3,2,1]
       ]

Thinking 

For the number of n, n-1 corresponds to the first number before the arrangement, this last number and then inserted into a different location

    def permute(self, nums: List[int]) -> List[List[int]]:
        if len(nums) == 0:
            return []
        elif len(nums) == 1:
            return [[nums[0]]]
        
        ans = []
        temp = self.permute(nums[1:])
        for item in temp:
            for i in range(len(item)+1):
                p = item.copy()
                p.insert(i,nums[0])
                ans.append(p)
    
        return ans    

 

Topic 47 Permutations II

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

Example:

    Input: [1,1,2]
    Output:
    [
       [1,1,2],
       [1,2,1],
       [2,1,1]
    ]

Thinking

Recursion is also inserted, but at the time of each insert a new number, if you encounter the same number and insert a number, you can terminate. Because of the back of the room, at the time of the last time you insert a digital has been considered and, side by side in the current item.

    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        if len(nums) == 0:
            return []
        elif len(nums) == 1:
            return [[nums[0]]]
        
        nums.sort()
        ans = []
        temp = self.permuteUnique(nums[1:])
        for item in temp:
            for i in range(len(item)+1):
                p = item.copy()
                p.insert(i,nums[0])
                ans.append(p)
                if i<len(item):
                    if nums[0] == item[i]:
                        break
        return ans               

 

发布了45 篇原创文章 · 获赞 1 · 访问量 3363

Guess you like

Origin blog.csdn.net/qq_22498427/article/details/104565582