[Leetcode] Permutations II
Permutations II 题解
题目来源:https://leetcode.com/problems/permutations-ii/description/
Description
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example
For example,
[1,1,2]
have the following unique permutations:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
Solution
class Solution {
private:
void dfs(vector<int>& nums, vector<bool>& used, vector<int>& path,
vector<vector<int> >& res) {
if (path.size() == nums.size()) {
res.push_back(path);
} else {
int size = nums.size();
for (int i = 0; i < size; i++) {
if (used[i])
continue;
if (i > 0 && nums[i] == nums[i - 1] && used[i - 1])
continue;
used[i] = true;
path.push_back(nums[i]);
dfs(nums, used, path, res);
path.pop_back();
used[i] = false;
}
}
}
public:
vector<vector<int> > permuteUnique(vector<int> &nums) {
vector<vector<int> > res;
vector<int> path;
vector<bool> used(nums.size(), false);
sort(nums.begin(), nums.end());
dfs(nums, used, path, res);
return res;
}
};
解题描述
这道题是Permutations的升级版本,要对给出的数组进行全排列,并且不能出现重复的解法。一开始没有想到怎么去标记重复,就直接套用第一版的解法然后在插入结果的时候遍历查重。之后看了评论区的解法之后才改进了解法:先对数组进行排序,然后进行DFS,过程中使用布尔数组used
进行染色,并且由于对数组已经进行了排序,查重的时候只需检查前一项是否与当前项相同且已经染色。