Open azl397985856 opened 5 months ago
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
ans = []
def dfs(x):
if x == len(nums)-1:
ans.append(list(nums))
return
dic = set()
for i in range(x, len(nums)):
if nums[i] in dic:
continue
dic.add(nums[i])
nums[i], nums[x] = nums[x], nums[i]
dfs(x+1)
nums[i], nums[x] = nums[x], nums[i]
dfs(0)
return ans
class Solution {
vector
public:
void backtrack(vector
vector<vector<int>> permuteUnique(vector<int>& nums) {
vector<vector<int>> ans;
vector<int> perm;
vis.resize(nums.size());
sort(nums.begin(), nums.end());
backtrack(nums, ans, 0, perm);
return ans;
}
};
class Solution:
def __init__(self):
self.ans = []
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
self.n = len(nums)
counter = collections.Counter(nums)
self.dfs(nums, [], counter)
return self.ans
def dfs(self, nums, path, counter):
if len(path) == self.n:
self.ans.append(path.copy())
for k in counter:
if counter[k] > 0:
path.append(k)
counter[k] -= 1
self.dfs(nums, path, counter)
path.pop()
counter[k] += 1
47 全排列 II
入选理由
暂无
题目地址
https://leetcode-cn.com/problems/permutations-ii/
前置知识
题目描述
示例:
输入: [1,1,2] 输出: [ [1,1,2], [1,2,1], [2,1,1]