码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-12-30 11:18:05      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:


题目来源


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

 

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

标签:

原文地址:http://www.cnblogs.com/loadofleaf/p/5087993.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!