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] ]
方法一:用到next_permutation
class Solution
{
public:
vector<vector<int>> permute(vector<int> &nums) {
vector<vector<int>> ans;
sort(nums.begin(), nums.end());
do {
vector<int> tmp;
for (int i = 0; i < nums.size(); i++)
tmp.push_back(nums[i]);
ans.push_back(tmp);
} while (next_permutation(nums.begin(), nums.end()));
return ans;
}
};
方法二:dfs(也是最原始的方法,next_permutation的产生方法)
class Solution {
public:
vector<vector<int>> ans;
vector<int> tmp;
void dfs(int depth, vector<int>& nums)
{
if(depth >= nums.size()-1)
{
tmp.clear();
for(int i=0; i<nums.size(); i++)
tmp.push_back(nums[i]);
ans.push_back(tmp);
return;
}
for(int i=depth; i<nums.size(); i++)
{
swap(nums[depth], nums[i]);
dfs(depth+1, nums);
swap(nums[depth], nums[i]);
}
}
vector<vector<int>> permute(vector<int>& nums)
{
dfs(0, nums);
return ans;
}
};