标签:table problems and lint accept esc numbers 复杂 bfs
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!
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)
#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
#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
均为非递归,但是没看懂,以后再看
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
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
[Lintcode]16. Permutations II/[Leetcode]47. Permutations II
标签:table problems and lint accept esc numbers 复杂 bfs
原文地址:https://www.cnblogs.com/siriusli/p/10386629.html