class Solution {
public:
vector<vector<int> > permute(vector<int> &num) {
vector<bool>used(num.size(),false);
vector<int>com;
vector<vector<int> >ret;
permuteRe(num,used,com,ret);
return ret;
}
void permuteRe(vector<int> &num, vector<bool>&used, vector<int>&com,vector<vector<int> >&ret){
if(com.size()==num.size()){
ret.push_back(com);
return;
}
for(int i=0;i<num.size();i++){
if(used[i]) continue;
used[i]=true;
com.push_back(num[i]);
permuteRe(num,used,com,ret);
used[i]=false;
com.pop_back();
}
}
};
//another flavor
vector<vector<int> > permute(vector<int> &num) {
vector<vector<int>> ps,lps; vector<int> p;
if (num.size()==0)
{
ps.push_back(p); return ps;
}
p.insert(p.begin(),num.begin()+1,num.end());
lps = permute(p);
for (int i=0;i<num.size();i++)
{
ps.insert(ps.end(),lps.begin(),lps.end());
for (int j=0;j<lps.size();j++)
ps[i*lps.size()+j].insert(ps[i*lps.size()+j].begin()+i,1,num[0]);
}
return ps;
}
// yet another one
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> res;
if(nums.size()==0) {res.push_back(vector<int>()); return res;}
for(int i=0;i<nums.size();i++){
int tmp=nums[i];
nums[i]=nums.back();
nums.pop_back();
vector<vector<int>> T = permute(nums);
for(int j=0;j<T.size();j++){
res.push_back(T[j]);
res.back().push_back(tmp);
}
nums.push_back(nums[i]);
nums[i]=tmp;
}
return res;
}
No comments:
Post a Comment