题目描述:

leetcode-46-全排列

方法一:回溯

class Solution:
    def permute(self, nums):
        n = len(nums)
        res = []
        def helper2(nums, temp_list, length):
            if length == n:
                res.append(temp_list)
            for i in range(len(nums)):
                helper2(nums[:i] + nums[i + 1:], temp_list + [nums[i]], length + 1)
        helper2(nums, [], 0)
        return res

另:

class Solution: 
    def permute(self, nums):
        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() 
        return output

 

相关文章:

  • 2022-12-23
  • 2021-09-27
  • 2021-06-20
  • 2021-08-29
  • 2021-08-25
  • 2022-12-23
  • 2022-01-09
猜你喜欢
  • 2021-08-14
  • 2020-04-26
  • 2021-07-23
  • 2021-07-22
  • 2021-08-09
  • 2021-06-02
相关资源
相似解决方案