标签:style blog http io ar color os sp for
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]
.
Backtracking
1 #include <vector> 2 #include <iterator> 3 #include <algorithm> 4 #include <iostream> 5 using namespace std; 6 7 class Solution { 8 public: 9 vector<vector<int> > permuteUnique(vector<int> &num) { 10 int n = num.size(); 11 vector<vector<int> >ret; 12 if(n<1) return ret; 13 if(n<2) {ret.push_back(num); return ret; } 14 sort(num.begin(),num.end()); 15 ret.push_back(num); 16 while(next_permutation(num.begin(),num.end())){ 17 ret.push_back(num); 18 } 19 return ret; 20 } 21 }; 22 23 int main() 24 { 25 vector<int> num = {1,1,2}; 26 Solution sol; 27 vector<vector<int> > ret = sol.permuteUnique(num); 28 for(int i=0;i<ret.size();i++){ 29 copy(ret[i].begin(),ret[i].end(),ostream_iterator<int>(cout," ")); 30 cout<<endl; 31 } 32 return 0; 33 }
如果不调用嘛,就是自己写一个next_permutation,在Permutations 写过好多个版本了,回顾下stl 的实现逻辑吧:
标签:style blog http io ar color os sp for
原文地址:http://www.cnblogs.com/Azhu/p/4148332.html