Given a list of numbers, return all possible permutations.
Example
For nums = [1,2,3]
, the permutations are:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
Challenge
Do it without recursion.
class Solution {
private:
void swap(vector<int> &nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
void permuteHelper(vector<int> &nums, int curIdx, vector<vector<int>> &retVtr) {
if (curIdx == nums.size())
{
retVtr.push_back(nums);
return;
}
for (int i=curIdx; i<nums.size(); i++)
{
swap(nums, curIdx, i);
permuteHelper(nums, curIdx+1, retVtr);
swap(nums, i, curIdx);
}
}
public:
/**
* @param nums: A list of integers.
* @return: A list of permutations.
*/
vector<vector<int> > permute(vector<int> nums) {
// write your code here
vector<vector<int>> retVtr;
if (nums.size() == 0)
return retVtr;
permuteHelper(nums, 0, retVtr);
return retVtr;
}
};