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].
利用了 Next Permutation 的函数方法。
class Solution {
public:
vector<vector<int> > permuteUnique(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int> > result;
sort(num.begin(),num.end());
result.push_back(num);
while(nextPermutation(num))
{
result.push_back(num);
}
return result;
}
bool nextPermutation(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int previous = -1;
int current = -1;
for(int i=0;i<num.size()-1;i++)
{
if(num[i]<num[i+1])
{
previous = i;
}
}
if(previous!=-1)
{
for(int j=previous;j<num.size();j++)
{
if(num[previous]<num[j])
{
current = j;
}
}
swap(num[previous],num[current]);
sort(num.begin()+previous+1,num.end());
return true;
}
else
{
return false;//代表已经没有更多的排列了
}
}
};
本文介绍了一种使用 C++ 实现的算法,该算法能够从可能包含重复元素的集合中找出所有不重复的全排列组合。通过使用 sort 和 nextPermutation 函数,确保了结果的唯一性和正确性。
178

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



