Given a list of numbers, return all possible permutations.
Challenge
Do it without recursion.
1.递归
class Solution {
public:
/**
* @param nums: A list of integers.
* @return: A list of permutations.
*/
vector<vector<int> > res;
void dfs(vector<int> &nums,vector<int> &sub,int cur){
if(cur==nums.size()){
res.push_back(sub);
return;
}
for(int i=0;i<nums.size();i++){
bool ok=true;
for(int j=0;j<cur;j++){
if(nums[i]==sub[j]){
ok=false;
}
}
if(ok){
sub[cur]=nums[i];
dfs(nums,sub,cur+1);
}
}
}
vector<vector<int> > permute(vector<int> nums) {
// write your code here
int len=nums.size();
if(len==0){
return res;
}
vector<int> sub(len);
dfs(nums,sub,0);
return res;
}
};
2.非递归
关于求下一个排列见以前的一篇博文 lintcode:Next Permutation
class Solution {
public:
/**
* @param nums: A list of integers.
* @return: A list of permutations.
*/
void nextPermutation(vector<int> &nums){
int len=nums.size();
if(len==1){
return;
}
int partitionIndex;
int in=len-1;
while(in){
if(nums[in-1]<nums[in]){
partitionIndex=in-1;
break;
}
in--;
}
//注意这里是in==0而不是partitionIndex==0;
//如果in==0,如果nums整个都是逆序的
if(in==0){
reverse(nums.begin(),nums.end());
}else{
int changeIndex;
for(int i=len-1;i>partitionIndex;i--){
if(nums[i]>nums[partitionIndex]){
changeIndex=i;
break;
}
}
swap(nums[partitionIndex],nums[changeIndex]);
reverse(nums.begin()+partitionIndex+1,nums.end());
}
}
int factorial(int n){
return (n==1||n==0)?1:factorial(n-1)*n;
}
vector<vector<int> > permute(vector<int> nums) {
// write your code here
vector<vector<int> > res;
if(nums.size()==0){
return res;
}
int sum=factorial(nums.size());
res.push_back(nums);
for(int i=1;i<sum;i++){
nextPermutation(nums);
res.push_back(nums);
}
return res;
}
};