[LeetCode]题解(python):046-Permutations


题目来源


https://leetcode.com/problems/permutations/

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

For example,
[1,2,3] have the following permutations:
[1,2,3][1,3,2][2,1,3][2,3,1][3,1,2], and [3,2,1].


题意分析


Input: a list 

Output: a permutations

Conditions:全排列


题目思路


递归解决。注意到python取list的若干位很方便,分片~然后仔细发现不单是全排序,而且还是字典序(因为每一次遍历都是从小到大的,遍历顺序取决~)


AC代码(Python)


 1 class Solution(object):
 2     def permute(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: List[List[int]]
 6         """
 7         if len(nums) == 1:
 8             return [nums]
 9         res = []
10         for i in range(len(nums)):
11             for j in self.permute(nums[:i] + nums[i+1:]):
12                 res.append([nums[i]] + j)
13         return res
原文地址:https://www.cnblogs.com/loadofleaf/p/5087993.html