注:
与39题的循环体进行比较
题目:
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
题解:
class Solution {
public:
vector<vector<int>> result;
vector<int> subnums;
bool judge(vector<int> judge_nums){
int size=judge_nums.size();
sort(judge_nums.begin(),judge_nums.end());
for(int i=0;i<size-1;i++){
if(judge_nums[i]==judge_nums[i+1]){
return false;
}
}
return true;
}
void dfs(vector<int>& nums){
if(subnums.size()==nums.size()){
if(judge(subnums)==true){
result.push_back(subnums);
}
return;
}
for(int i=0;i<nums.size();i++){
subnums.push_back(nums[i]);
dfs(nums);
subnums.pop_back();
}
}
vector<vector<int>> permute(vector<int>& nums) {
int index=0;
dfs(nums);
return result;
}
};
官方题解:
省去了判断重复元素的函数,用一个bool类型的vector代替
class Solution {
public:
vector<vector<int>> result;
vector<int> subnums;
void dfs(vector<int>& nums,vector<bool>& judge){
if(subnums.size()==nums.size()){
result.push_back(subnums);
return;
}
for(int i=0;i<nums.size();i++){
if(judge[i]==true) {
continue;
}
judge[i]=true;
subnums.push_back(nums[i]);
dfs(nums,judge);
subnums.pop_back();
judge[i]=false;
}
}
vector<vector<int>> permute(vector<int>& nums) {
int index=0;
vector<bool> judge(nums.size(),false);
dfs(nums,judge);
return result;
}
};