Given a collection of 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> &num)
{
vector<vector<int>> result;
helper(num, result, 0, num.size());
return result;
}
static void helper(vector<int> &num,vector<vector<int>> &result, int current, int len)
{
if (current == len)
{
result.push_back(num);
return;
}
for (int i = current; i < len; i++)
{
swap(num[current], num[i]);
helper(num, result, current + 1, len);
swap(num[current], num[i]);
}
}
static void swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
};