题目:
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].
class Solution {
public:
vector<vector<int> > permuteUnique(vector<int> &num) {
res.clear();
memset(used, false, sizeof(used));
sort(num.begin(), num.end());
dfs(0, num.size(), num);
return res;
}
private:
vector<vector<int> > res;
bool used[100];
int a[100];
void dfs(int dep, int maxDep, vector<int> &num) {
if (dep == maxDep) {
vector<int> tt;
for (int i = 0; i < maxDep; i++)
tt.push_back(a[i]);
res.push_back(tt);
return;
}
for (int i = 0; i < maxDep; i++) {
if (!used[i]) {
if (i != 0 && num[i] == num[i - 1] && !used[i - 1])
continue;
used[i] = true;
a[dep] = num[i];
dfs(dep + 1, maxDep, num);
used[i] = false;
}
}
}
};
本文介绍了一个C++算法解决方案,用于从可能包含重复元素的整数集合中生成所有唯一的排列组合。通过使用深度优先搜索(DFS)策略,并对输入数组进行排序以跳过重复元素,确保了结果集中没有重复的排列。
651

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



