1、全排列
class Solution {
public:
vector<vector<int>> ret;
vector<int> path;
bool check[7];
void dfs(vector<int>& nums)
{
if(nums.size() == path.size())
{
ret.push_back(path);
return;
}
for(int i = 0;i < nums.size();i++){
if(check[i] == false)
{
path.push_back(nums[i]);
check[i] = true;
dfs(nums);
//回溯
path.pop_back();
check[i] = false;
}
}
}
vector<vector<int>> permute(vector<int>& nums) {
dfs(nums);
return ret;
}
};
2、子集
解法一:根据每个元素选/不选来思考:
解法二:根据元素个数来思考:
class Solution {
public:
vector<int> path;
vector<vector<int>> ret;
vector<vector<int>> subsets(vector<int>& nums) {
dfs(nums,0);
return ret;
}
void dfs(vector<int>& nums,int pos)
{
ret.push_back(path);
for(int i = pos;i < nums.size();i++){
path.push_back(nums[i]);
dfs(nums,i+1);
path.pop_back();
}
}
};