47. Permutations II (全排列有重复的元素)

时间:2023-03-09 15:31:40
47. Permutations II (全排列有重复的元素)
Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:

[
[1,1,2],
[1,2,1],
[2,1,1]
] 与上一题不同,就是在19行加个判断即可。
 class Solution(object):
def __init__(self):
self.res = [] def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
self.help(nums, 0, len(nums)) return self.res def help(self, a, lo, hi):
if(lo == hi):
self.res.append(a[0:hi])
for i in range(lo, hi):
#判断 i 是否已经在当过头元素了
if a[i] not in a[lo:i]:
self.swap(a, i, lo)
self.help(a, lo + 1, hi)
self.swap(a, i, lo)
def swap(self, a, i, j):
temp = a[i]
a[i] = a[j]
a[j] = temp