46Permutations

一个数组,里面的数字各不相同,排列出其所有可能

方法很多,能想出来的有:

1,排列所有可能,每出现一种就加入到数组中

2,假设有n个数字,先排列出前n-1数字的可能情况,再将最后一个数字加入

我用的第二种

class Solution:
    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        result = [[]]
        for i, num in enumerate(nums):
            tmp = []
            for line in result:
                tmp.extend([line[:j]+[num]+line[j:] for j in range(i+1)])
            result = tmp
        return result

再精简一下:

class Solution:
    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        result = [[]]
        for i, num in enumerate(nums):
            result = [line[:j]+[num]+line[j:] for j in range(i+1) for line in result]
        return result
原文地址:https://www.cnblogs.com/mangmangbiluo/p/10154417.html