47. Permutations II (题目链接)
Medium
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example:
Input: [1,1,2] Output: [ [1,1,2], [1,2,1], [2,1,1] ]
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
book = [0] * len(nums)
rlt = []
nums.sort()
def dfs(cnt, permu):
if cnt == len(nums):
rlt.append(copy.deepcopy(permu))
return
i = 0
while i < len(nums):
if book[i] == 0:
permu.append(nums[i])
book[i] = 1
dfs(cnt + 1, permu)
permu.pop()
book[i] = 0
while i + 1 < len(nums) and nums[i] == nums[i + 1]:
i += 1
i += 1
dfs(0, [])
return rlt
本文介绍了一种解决含重复元素列表的全排列问题的算法。通过使用深度优先搜索(DFS)并结合列表排序和跳过重复元素的方法,有效地生成所有可能的不重复全排列组合。示例中给出了输入[1,1,2]时的预期输出。
870

被折叠的 条评论
为什么被折叠?



