46 Permutations
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],
[3,2,1]
]
Solution (recursive):
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
int n = nums.size();
vector<vector<int>> res;
if ( n == 0 ) {
vector<int> tmp;
res.push_back(tmp);
return res;
}
for ( int i = 0; i <= n-1; i++) {
vector<int> tmp;
for ( int j = 0; j <= n-1; j++ ) {
if ( i != j ) tmp.push_back(nums[j]);
}
vector<vector<int>> tmp_res = permute(tmp);
int nres = tmp_res.size();
for ( int j = 0; j <= nres-1; j++ ) {
tmp = tmp_res[j];
tmp.push_back(nums[i]);
res.push_back(tmp);
}
}
return res;
}
};
Solution (iterative):???