Given a collection of numbers that might contain duplicates, return all possible unique permutations.
此题和上一道46的差别在于此题中给出的有重复的数字
因为next_permutation求解的是下一个全排列,因此不会出现重复的现象
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector<vector<int>> permuteduplicate(vector<int> &nums){
sort(nums.begin(),nums.end());//一定要先对nums排序
vector<vector<int>> res;
res.push_back(nums);
while(next_permutation(nums.begin(),nums.end()){//只有nums有下一个全排列时才进行循环,此时nums已改变
res.push_back(nums);
}
return res;
}
int main(){
vector<int> nums;
nums.push_back(1);
nums.push_back(2);
nums.push_back(3);
vector<vector<int>> m = permute(nums);
int len= m.size();
for(int i =0;i<len;++i){//输出
int len1 = data[i].size();
for(int j = 0;j<len1;++j){
cout<<m[i][j]<<","
}
cout<<m[i][len1-1]<<endl;
}
return 0;
}
参考: