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

 

posted @ 2019-07-11 15:25  oldby  阅读(206)  评论(0)    收藏  举报