leetcode python 46. 全排列(中等、数组、回溯)

给定一个没有重复数字的序列,返回其所有可能的全排列。

示例:
输入: [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]]
        """
        from itertools import permutations
        return list(permutations(nums))

执行用时: 56 ms, 在Permutations的Python3提交中击败了99.32% 的用户

方法二:用了递归的方法

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

执行用时: 80 ms, 在Permutations的Python3提交中击败了37.65% 的用户

方法三:添加了一个判断是否经过的标志,在一个全排列中,如果经过了,则继续看其他的数字,如果没有经过,就从这个数字开始。

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

执行用时: 64 ms, 在Permutations的Python3提交中击败了89.62% 的用户

知识点总结:
1.使用Python random模块的choice方法随机选择某个元素

f = ['a', 'b', 'c', 'd', 'e']
from random import choice
print choice(f)

2.使用python random模块的sample函数从列表中随机选择一组元素

list1= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
slice = random.sample(list1, 5) 
#从list中随机获取5个元素,作为一个片断返回 
print(slice)
print(list1)
 #原有序列并没有改变。

3.xrange() 函数用法与 range 完全相同,所不同的是生成的不是一个数组,而是一个生成器。

>>>xrange(8)
xrange(8)
>>> list(xrange(8))
[0, 1, 2, 3, 4, 5, 6, 7]
>>> range(8)                 # range 使用
[0, 1, 2, 3, 4, 5, 6, 7]
>>> xrange(3, 5)
xrange(3, 5)
>>> list(xrange(3,5))
[3, 4]
>>> range(3,5)               # 使用 range
[3, 4]
>>> xrange(0,6,2)
xrange(0, 6, 2)              # 步长为 2
>>> list(xrange(0,6,2))
[0, 2, 4]
>>>

猜你喜欢

转载自blog.csdn.net/weixin_42234472/article/details/84785003
今日推荐