Leetcode 47.全排列 II
1 题目描述(Leetcode题目链接)
给定一个可包含重复数字的序列,返回所有不重复的全排列。
输入: [1,1,2]
输出:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
2 题解
本题与46题全排列要求类似,输入变为了包含重复数字,并要求输出中不包含重复的排列,因此在第46题的基础上,在每一个层级上入栈的时候加上判断重复元素是否已经入栈过即可。另外需要在最开始对数组进行升序排序。
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
length = len(nums)
nums.sort()
retv = []
def backward(i, stack, candidates):
if len(stack) == length:
retv.append(stack)
return
for j in range(0, len(candidates)):
if j == 0 or candidates[j] != candidates[j-1]: #判断是否重复入栈相同元素
backward(j, stack + [candidates[j]], candidates[:j] + candidates[j+1:])
backward(0, [], nums)
return retv