[Lintcode]16. Permutations II/[Leetcode]47. Permutations II
Posted siriusli
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Lintcode]16. Permutations II/[Leetcode]47. Permutations II相关的知识,希望对你有一定的参考价值。
16. Permutations II/47. Permutations II
- 本题难度: Medium
- Topic: Search & Recursion
Description
Given a list of numbers with duplicate number in it. Find all unique permutations.
Example
Example 1:
Input: [1,1]
Output:
[
[1,1]]
Example 2:
Input: [1,2,2]
Output:
[
[1,2,2],
[2,1,2],
[2,2,1]]
Challenge
Using recursion to do it is acceptable. If you can do it without recursion, that would be great!
我的代码
法1: 递归 BFS
class Solution:
"""
@param: : A list of integers
@return: A list of unique permutations
"""
#recursion
#dfs
def permuteUnique(self, nums):
# write your code here
nums.sort()
res = []
n = len(nums)
self.dfs(nums,[],res,n)
return res
def dfs(self,nums,path,res,n):
if len(path) == n:
res.append(path)
for i in range(len(nums)):
if i>0 and nums[i-1]==nums[i]:
continue
self.dfs(nums[:i]+nums[i+1:],path+[nums[i]],res,n)
法2 非递归 DFS
#no recursion
def permuteUnique(self, nums):
# write your code here
res = []
nums.sort()
containt = [[[], nums]]
while (len(containt) > 0):
[l1, l2] = containt.pop()
if len(l2) == 0:
res.append(l1)
for i in range(len(l2)):
if i > 0 and l2[i - 1] == l2[i]:
continue
containt.append([l1 + [l2[i]], l2[:i] + l2[i + 1:]])
return res
法3: 非递归,BFS
#BFS
def permuteUnique(nums):
# write your code here
res = []
nums.sort()
containt = collections.deque([[[], nums]])
while (len(containt) > 0):
[l1, l2] = containt.popleft()
print(‘l1‘,l1,‘l2‘,l2)
if len(l2) == 0:
res.append(l1)
for i in range(len(l2)):
if i > 0 and l2[i - 1] == l2[i]:
continue
containt.append([l1 + [l2[i]], l2[:i] + l2[i + 1:]])
return res
别人的代码
均为非递归,但是没看懂,以后再看
1
def permuteUnique(self, nums):
ans = [[]]
for n in nums:
new_ans = []
for l in ans:
for i in range(len(l)+1):
new_ans.append(l[:i]+[n]+l[i:])
if i<len(l) and l[i]==n: break #handles duplication
ans = new_ans
return ans
2
def permute(nums):
permutations = [[]]
for head in nums:
permutations = [rest[:i]+[head]+rest[i:] for rest in permutations for i in range(len(rest)+1)]
return permutations
思路
递归比较好理解,DFS。
用栈是DFS
用队列是BFS
- 时间复杂度 O(n!)
以上是关于[Lintcode]16. Permutations II/[Leetcode]47. Permutations II的主要内容,如果未能解决你的问题,请参考以下文章
lintcode-medium-Next Permutation II
lintcode-medium-Permutation Index II
lintcode-medium-Permutation Sequence
[Lintcode]52. Next Permutation