46. Permutations
Description:
Given a collection of distinct integers, return all possible permutations.
Difficulty:Medium
Example:
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
方法:Recursive
- Time complexity : O ( n ! ) O\left ( n! \right ) O(n!)
- Space complexity :
O
(
n
!
)
O\left ( n! \right )
O(n!)
思路:
此题目进阶版是字符串的全排列,而且里面有重复,可以参考:
字符串全排列,去重。
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> res;
helper(nums, 0, res);
return res;
}
void helper(vector<int>& nums, int begin, vector<vector<int>> &res) {
if (begin >= nums.size()) {
res.push_back(nums);
return ;
}
for (int i = begin; i < nums.size(); i++) {
swap(nums[i], nums[begin]);
helper(nums, begin + 1, res);
swap(nums[i], nums[begin]);
}
}
};