问题:
Given a collection of numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
Solution:
#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
vector<vector<int> > permute(vector<int> &num)
{
vector<vector<int> > resultVector;
sort(num.begin(),num.end());//STL algorithm funtion
do
{
vector<int> vOne;
for(int i=0;i<num.size();i++)
vOne.push_back(num[i]);
resultVector.push_back(vOne);
}while(next_permutation(num.begin(),num.end()));//next_permutation you can find in STL
return resultVector;
}
vector<vector<int> > permuteOrder(int n)
{
vector<int> num;
for(int i=1;i<=n;i++)
num.push_back(i);
return permute(num);
}
void printCollection(vector<vector<int> > &vResult)
{
for(vector<vector<int> >::const_iterator iter = vResult.begin();iter!=vResult.end();iter++)
{
for(vector<int>::const_iterator it = (*iter).begin();it!=(*iter).end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
}
};
int main()
{
vector<int> num ;
num.push_back(1);
num.push_back(3);
num.push_back(2);
Solution so;
cout<<"permutation"<<endl;
vector<vector<int> > vResult = so.permute(num);
so.printCollection(vResult);
cout<<"order permutation"<<endl;
vector<vector<int> > vOrderResult = so.permuteOrder(3);
so.printCollection(vOrderResult);
return 0;
}