Given a collection of distinct 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]
.
Easy question, but should be careful when it comes to a solution using recursion.
Two solutions.
- Using recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
vector<vector<int> > permute(vector<int>& nums){ | |
vector<vector<int> > results; | |
if(nums.size()==1){ | |
vector<int> r; | |
r.push_back(nums[0]); | |
results.push_back(r); | |
return results; | |
} | |
for(int i=0; i<nums.size(); ++i){ | |
vector<int> newnums=nums; | |
newnums.erase(newnums.begin()+i); | |
vector<vector<int> >tmpresults=permute(newnums); | |
for(int j=0; j<tmpresults.size(); ++j){ | |
vector<int> tmptmpr=tmpresults[j]; | |
tmptmpr.insert(tmptmpr.begin(), nums[i]); | |
results.push_back(tmptmpr); | |
} | |
} | |
return results; | |
} |
- Not using recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
vector<vector<int> > permute(vector<int>& nums){ | |
vector<vector<int> > results(1, vector<int>(1, nums[0])); | |
for(int i=1; i<nums.size(); ++i){ | |
int v=nums[i]; | |
vector<vector<int> > tmpresults; | |
for(int j=0; j<results.size(); ++j){ | |
for(int k=0; k<=results[j].size(); ++k){ | |
vector<int> r=results[j]; | |
r.insert(r.begin()+k, v); | |
tmpresults.push_back(r); | |
} | |
} | |
results=tmpresults; | |
} | |
return results; | |
} | |
}; |
No comments:
Post a Comment