[leetcode] permutations 排列
写了两个,一个是直接的递归实现:
class Solution { public: void swap(vector<int> &num,int left,int right) { num[left] = num[left]^num[right]; num[right] = num[left]^num[right]; num[left] = num[left]^num[right]; } void permuteHelp(vector<int> &num,int fix,vector< vector<int> > &result) { if(fix==num.size()-1) { result.push_back(num); return; } permuteHelp(num,fix+1,result); for(int i=fix+1;i<num.size();i++) { swap(num,i,fix); permuteHelp(num,fix+1,result); swap(num,i,fix); } } vector<vector<int> > permute(vector<int> &num) { vector< vector<int> > result; if (num.size()<1) return result; if(num.size()<2) result.push_back(num); else permuteHelp(num,0,result); return result; } };
另外一个是通过类似STL 的 next_permutation 函数方法实现:
下面链接是 STL 的 next_permutation 函数 描述:
http://www.cnblogs.com/Azhu/articles/3897586.html
按字典左起从小到达顺序给出当前序列的下一个排序,适用于序列中有重复元素的情况,函数的过程是:
1.右起寻找相邻的两数,满足next<next1
2.右起寻找第一个大于next的数,记为mid
3.交换 mext 与mid
4.逆序next1 (包括next1)到右末尾
class Solution{ public: int factorial(int n) { return n<2?1:factorial(n-1)*n; } void next_per(vector<int> & num) { vector<int>::iterator first,last,next,next1,mid; first = num.begin(); last = num.end(); next = last; if(first==--next||first==last) return ; while(1) { next1=next--; if(*next<*next1) { mid = last; while(!(*next<*--mid)); iter_swap(next,mid); reverse(next1,last); return ; } if(next==first) { reverse(first,last); return ; } } } vector< vector<int> > permute(vector<int> &num) { vector< vector<int> > result; if(num.size()<1) return result; sort(num.begin(),num.end()); result.push_back(num); for(int i=1;i<factorial(num.size());i++) { next_per(num); result.push_back(num); } return result; } };
main函数:
#include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { vector<int> num; int a = 2; for(int i=0;i<a;i++) num.push_back(i); Solution solution; vector< vector<int> > result; result = solution.permute(num); for(int id = 0;id<result.size();id++) { for(int i=0;i<a;i++) cout<<result[id][i]<<' '; cout<<endl; } cout<<result.size()<<endl; return 0; }