leetcode46. 全排列

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_36811967/article/details/86535300

给定一个没有重复数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]

暴力法时间还不错:

class Solution:
    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        if not nums:
            return []
        if len(nums) == 1:
            return [nums]
        res = []
        for i in range(len(nums)):
            for one in self.permute(nums[0:i] + nums[i + 1:]):
                res.append([nums[i]] + one )
        return res

回溯:

class Solution:
    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res, length, one = [], len(nums), []
        visited = [0]*length  # 是否访问过
        def helper(count):
            if count == length:
                # 注意这里直接是one的话res里list会为空,因为最后one为[]
                res.append(one.copy())
                return
            for i in range(length):
                if visited[i] == 0:
                    one.append(nums[i])
                    visited[i] = 1
                    helper(count+1)
                    visited[i] = 0
                    one.remove(nums[i])
        helper(0)
        return res

优化版的回溯,不需要标记数组:

class Solution:
    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res, length, one = [], len(nums), []
        def helper(count):
            if count == length:
                # 注意这里直接是one的话res里list会为空,因为最后one为[]
                res.append(one.copy())
                return
            for i in range(count, length):
                one.append(nums[i])
                nums[i], nums[count] = nums[count], nums[i]
                helper(count+1)
                nums[i], nums[count] = nums[count], nums[i]
                one.remove(nums[i])
        helper(0)
        return res

猜你喜欢

转载自blog.csdn.net/sinat_36811967/article/details/86535300
今日推荐