Tencent 43- Full arrangement

Tencent 43- fully arranged leetcode46

Given a sequence without repeated numbers, return all possible permutations of it.

Example:

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

  • At first glance, it is a retrospective question, but it is actually a little harder than a subset question
  • Follow the normal backtracking, maybe O (N! * N)
  • But this question is the best but backtracking can still do O (N!)
  • But at this time, the backtracking writing method is a bit different from the past. Here, the backtracking is based on exchange. The backtracking of exchange is used. The swap swap needs to be written twice, wrapping around the recursive original function. Just know this thing
  • The practice is that the first bit is swapped with all subsequent bits, the second bit is swapped with all subsequent bits, and the third bit is swapped with all subsequent bits,
  • The xxth bit is represented by the variable first. When the xxth bit is replaced by the last bit, it can be output. first == n
class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        ##一看就是回溯的题,其实比子集题目难一点
        ##按正常的回溯做,可能是O(N!*N的)
        #但这题最好但回溯仍可以做到O(N!的)
        ##但此时回溯写法和以往有点不一样,这里但回溯是基于交换的,用到交换的回溯,交换swap需要写两遍,在递归原函数前后环绕。知道这个东西即可
        ##做法是,第一位和后面的所有位交换,第二位和后面的所有位交换,第3位和后面的所有位交换,
        ##第xx位 用变量first表示,当第xx位 被置换到最后一位去了的时候,可以输出了。first == n: 
        def backtrack(first = 0):
            # if all integers are used up
            if first == n:  
                output.append(nums[:])
            for i in range(first, n):
                # place i-th integer first 
                # in the current permutation
                nums[first], nums[i] = nums[i], nums[first]
                # use next integers to complete the permutations
                backtrack(first + 1)
                # backtrack
                nums[first], nums[i] = nums[i], nums[first]
        
        n = len(nums)
        output = []
        backtrack(0)
        return output 
Published 93 original articles · praised 8 · 10,000+ views

Guess you like

Origin blog.csdn.net/zlb872551601/article/details/103652236