# LeetCode--Permutations II 全排列之二

2018-01-25 10:57:27来源:网络收集作者:管理员人点击

[var1]

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], and [2,1,1].

对于if (i > 0 && num[i] == num[i - 1] && visited[i - 1] == 0) continue;的理解：

class Solution {
public:
vector > permuteUnique(vector &num) {
vector > res;
vector out;
vector visited(num.size(), 0);
sort(num.begin(), num.end());
permuteUniqueDFS(num, 0, visited, out, res);
return res;
}
void permuteUniqueDFS(vector &num, int level, vector &visited, vector &out, vector > &res) {
if (level >= num.size()) res.push_back(out);
else {
for (int i = 0; i < num.size(); ++i) {
if (visited[i] == 0) {
if (i > 0 && num[i] == num[i - 1] && visited[i - 1] == 0) continue;
visited[i] = 1;
out.push_back(num[i]);
permuteUniqueDFS(num, level + 1, visited, out, res);
out.pop_back();
visited[i] = 0;
}
}
}
}
};

class Solution {
public:
vector> permuteUnique(vector& nums) {
set> res;
permute(nums, 0, res);
return vector> (res.begin(), res.end());
}
void permute(vector &nums, int start, set> &res) {
if (start >= nums.size()) res.insert(nums);
for (int i = start; i < nums.size(); ++i) {
if (i != start && nums[i] == nums[start]) continue;
swap(nums[i], nums[start]);
permute(nums, start + 1, res);
swap(nums[i], nums[start]);
}
}
};