class Solution {
public:
vector<vector<int>> res;
bool check[7] = {false};
vector<int> path;
vector<vector<int>> permute(vector<int>& nums) {
dfs(nums);
return res;
}
void dfs(vector<int>& nums){
if(path.size() == nums.size()){
res.push_back(path);
return;
}
for(int i = 0; i < nums.size(); ++i){
if(!check[i]){
path.push_back(nums[i]);
check[i] = true;
dfs(nums);
// recovery
path.pop_back();
check[i] = false;
}
}
}
};
子集
法一:
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
vector<vector<int>> subsets(vector<int>& nums) {
dfs(nums, 0);
return res;
}
void dfs(vector<int>& nums, int i) {
if (nums.size() == i) {
res.push_back(path);
return;
}
dfs(nums,i+1);
path.push_back(nums[i]);
dfs(nums,i+1);
path.pop_back();// 恢复现场
}
};
法二:
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
vector<vector<int>> subsets(vector<int>& nums) {
dfs(nums, 0);
return res;
}
void dfs(vector<int>& nums, int pos){
if(pos == nums.size()){
res.push_back(path);
return;
}
dfs(nums,pos+1);
path.push_back(nums[pos]);
dfs(nums,pos+1);
path.pop_back();//恢复现场
}
};