Likou - full arrangement

topic

Given an array without duplicate numbers  nums , return  all possible permutations  . You can  return answers in any order  .

Example 1:

**Input: **nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1], [3,1,2],[3,2,1]]

Example 2:

**Input: **nums = [0,1]
Output: [[0,1],[1,0]]

Example 3:

**Input: **nums = [1]
Output: [[1]]

Ideas

The DFS version of the sub-question lasts five minutes and seconds. It is essentially DFS state transfer + state backtracking + termination condition processing. For this question, it is necessary to consider that each time a number is selected, a table is needed to record the number that has been selected. Each time you select something that has not been selected, and DFS will backtrack the status and reset the selection to empty. Note that List.copy is used here, otherwise problems will occur if the reference is only saved and no new List is generated, and List. Copy is only a shallow copy. Please note that you must copy at the appropriate time.

code

class Solution:

    def permute(self, nums: List[int]) -> List[List[int]]:

        lenNums = len(nums)

        numsTab = {}

        for v in nums:

            numsTab[v] = -1

        ans = []

        def DFS(cur):

            if(len(cur) == lenNums):

                ans.append(cur)

                return

            for i in range(0,lenNums):

                if(numsTab[nums[i]] == -1):

                    numsTab[nums[i]] = 1

                    tempList = cur.copy()

                    tempList.append(nums[i])

                    DFS(tempList)

                    numsTab[nums[i]] = -1

        DFS([])

        return ans

Guess you like

Origin blog.csdn.net/TongOuO/article/details/132288718