LeetCode46:Permutations

Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

LeetCode:链接

剑指offer同题:剑指Offer_编程题27:字符串的排列(全排列)

穷举一个集合的全排列,但是题目中说是distinct的数,所以没有重复的出现,不需要sort,相对简单。

化复杂为简单,如何找到解这道题的通式呢?和青蛙跳台阶的思路一样,无论给定的数组长度多少,其排列出来的组合样式均可以分解为“第一个数字+剩下的数组”的样式。可以通过遍历分别赋予第一位上不同的数字,那“剩下的数组”又可以如上分解。

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

猜你喜欢

转载自blog.csdn.net/mengmengdajuanjuan/article/details/85983854