LeetCode——Permutations
1. Question
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]
]
2. Solution
递归求解。
Basic idea: permutation of A[1..n] equals to
A[1] + permutation of (A[1..n] - A[1])
A[2] + permutation of (A[1..n] - A[2])
...
A[n] + permutation of (A[1..n] - A[n]).
3. Code
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> res;
permuteCore(nums, 0, res);
return res;
}
void permuteCore(vector<int>& nums, int start, vector<vector<int>>& res) {
if (start >= nums.size()) { // 已经遍历到最后一个数字
res.push_back(nums);
return;
}
// 依次和开始的数字交换
for (int i = start; i < nums.size(); i++) {
swap(nums[start], nums[i]);
permuteCore(nums,start + 1, res);
swap(nums[start], nums[i]); // 还原
}
}
};