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]
.
方法一:
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int> > result;
sort(nums.begin(),nums.end());
vector<int> tmp = nums;
// 全排列的下一排列
result.push_back(nums);
nextPermutation(nums);
while(nums!= tmp){
result.push_back(nums);
nextPermutation(nums);
}//while
return result;
}
void nextPermutation(vector<int>& nums) {
if (nums.size() < 2) return;
int i = nums.size() - 2;
int k ;
while(nums[i] >= nums[i + 1])
{
i--;
}
//若不存在子升序,则说明当前排列是最大排列,此时i = -1,下一排列即是最小排列,翻转整个序列即可
if (i < 0)
{
reverse(nums.begin() , nums.end());
return;
}
//找到了子升序
for (k = nums.size() - 1; i >= 0 && k > i ; --k)
if (nums[i] < nums[k])
break;
if (i >= 0)
{
swap(nums[i], nums[k]);
reverse(nums.begin() + i + 1, nums.end());
return;
}
}
};class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int> > result;
sort(nums.begin(),nums.end());
vector<int> tmp = nums;
// 全排列的下一排列
result.push_back(nums);
nextPermutation(nums);
while(nums!= tmp){
result.push_back(nums);
nextPermutation(nums);
}//while
return result;
}
void nextPermutation(vector<int>& nums) {
if (nums.size() < 2) return;
int i = nums.size() - 2;
int k ;
while(nums[i] >= nums[i + 1])
{
i--;
}
//若不存在子升序,则说明当前排列是最大排列,此时i = -1,下一排列即是最小排列,翻转整个序列即可
if (i < 0)
{
reverse(nums.begin() , nums.end());
return;
}
//找到了子升序
for (k = nums.size() - 1; i >= 0 && k > i ; --k)
if (nums[i] < nums[k])
break;
if (i >= 0)
{
swap(nums[i], nums[k]);
reverse(nums.begin() + i + 1, nums.end());
return;
}
}
};
方法二:
class Solution {
public:
vector<vector<int> > permute(vector<int> &num) {
vector<vector<int> > ret;
Helper(ret, num, 0);
return ret;
}
void Helper(vector<vector<int> >& ret, vector<int> num, int pos)
{
if(pos == num.size()-1)
ret.push_back(num);
else
{
for(int i = pos; i < num.size(); i ++)
{//swap all the ints to the current position
swap(num[pos], num[i]);
Helper(ret, num, pos+1);
swap(num[pos], num[i]);
}
}
}
};