Permutations and Permutations II
Permutations
问题:给定一个无重复元素的数组,输出其中元素可能的所有排列
示例:
输入:[2,3,4]
输出:[
[2,3,4],
[2,4,3],
[3,2,4],
[3,4,2],
[4,2,3],
[4,3,2]
]
解决思路:循环加递归
class Solution(object): def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ self.out = [] self.per(nums) return self.out def per(self,nums,one_per=[]): if not nums: self.out.append(one_per) return for i in nums: remain = nums[:] remain.remove(i) self.per(remain,one_per+[i])
Permutations II
问题:给定一个可能带有重复元素的数组,输出其元素可能的所有排列,不能重复输出
示例:
输入:[1,2,1]
输出:[
[1,1,2],
[1,2,1],
[2,1,1]
]
Python代码:
class Solution(object): def permuteUnique(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ self.out = [] nums.sort() self.per(nums) return self.out def per(self,nums,one_per=[]): if not nums: self.out.append(one_per) return for i in range(len(nums)): if i > 0 and nums[i] == nums[i-1]: continue self.per(nums[:i]+nums[i+1:],one_per+[nums[i]])