https://leetcode-cn.com/problems/TVdhkn/
class Solution {
public:
void dfs(vector<int>& nums,vector<vector<int>>& res,vector<int>& path,int len,int index){
if(len==nums.size()+1) return;
if(path.size()==len){
res.push_back(path);
len++;
}
for(int i=index;i<nums.size();i++){
path.push_back(nums[i]);
dfs(nums,res,path,len,i+1);
path.pop_back();
}
return;
}
vector<vector<int>> subsets(vector<int>& nums) {
int n = nums.size();
vector<vector<int>> res;
vector<int> path;
dfs(nums,res,path,0,0);
return res;
}
};
https://leetcode-cn.com/problems/7p8L0Z/
class Solution {
public:
void dfs(vector<int>& nums,vector<vector<int>>& res,vector<int>& path,vector<int>& flag){
if(path.size()==nums.size()){
res.push_back(path);
return;
}
for(int i=0;i<nums.size();i++){
if(flag[i]) continue;
if(i>0 && !flag[i-1] && nums[i]==nums[i-1]) continue;
path.push_back(nums[i]);
flag[i]=true;
dfs(nums,res,path,flag);
flag[i]=false;
path.pop_back();
}
}
vector<vector<int>> permuteUnique(vector<int>& nums) {
vector<vector<int>> res;
vector<int> path;
vector<int> flag(nums.size(),false);
sort(nums.begin(),nums.end());
dfs(nums,res,path,flag);
return res;
}
};
class Solution {
public:
void backtrack(int n,int left,int right,vector<string>& res,string s){
if(s.length()==2*n){
res.push_back(s);
return;
}
if(left<n){
s.push_back('(');
left++;
backtrack(n,left,right,res,s);
s.pop_back();
left--;
}
if(right<left){
s.push_back(')');
right++;
backtrack(n,left,right,res,s);
s.pop_back();
right--;
}
}
vector<string> generateParenthesis(int n) {
vector<string> res;
string s;
backtrack(n,0,0,res,s);
return res;
}
};
class Solution {
public:
int count = 0;
void backtrack(vector<int>& nums,int target,int sum,int index){
if(index==nums.size()){
if(sum==target) count++;
}else{
backtrack(nums,target,sum+nums[index],index+1);
backtrack(nums,target,sum-nums[index],index+1);
}
}
int findTargetSumWays(vector<int>& nums, int target) {
backtrack(nums,target,0,0);
return count;
}
};
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int target) {
int sum=0;
for(int i=0;i<nums.size();i++){
sum += nums[i];
}
int diff = sum-target;
if(diff<0 || diff%2!=0) return 0;
diff = diff/2;
int n = nums.size();
vector<vector<int>> dp(n+1,vector<int>(diff+1,0));
dp[0][0]=1;
for(int i=1;i<=n;i++){
for(int j=0;j<=diff;j++){
if(j<nums[i-1]) dp[i][j] = dp[i-1][j];
else dp[i][j] = dp[i-1][j]+dp[i-1][j-nums[i-1]];
}
}
return dp[n][diff];
}
};