腾讯//全排列
给定一个没有重复数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3] 输出: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
class Solution {
public:
void permute(vector<int>&nums, vector<vector<int>> &ans, int begin,int end){
if(begin == end){
ans.push_back(nums);
return ;
}else{
for(int i = begin; i <= end; i++){
swap(nums, begin, i);
permute(nums,ans,begin+1,end);
swap(nums,begin,i);
}
}
}
void swap(vector<int> &nums, int k,int i){
int temp = nums[k];
nums[k] = nums[i];
nums[i] = temp;
}
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> ans;
int len = nums.size()-1;
permute(nums, ans, 0, len);
return ans;
}
};
class Solution {
public:
void permute(vector<int>nums, vector<vector<int>>& ans, int begin, int end){
if(begin > end){
ans.push_back(nums);
return;
}else{
for(int i = begin; i <= end; i++){
swap(nums[begin], nums[i]);
permute(nums, ans, begin+1, end);
}
}
}
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> ans;
int len = nums.size()-1;
permute(nums, ans, 0, len);
return ans;
}
};