combination sum(I, II, III, IV)

时间:2023-05-04 13:31:44

II 简单dfs

 vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {

         vector<vector<int>> ans;
vector<int> cur;
sort(candidates.begin(), candidates.end()); // 排序后去重
dfs(,target,candidates,cur,ans);
return ans;
}
void dfs(int level, int target, vector<int>& candidates,vector<int>& cur,vector<vector<int>> &ans)
{
if(target==)
{
ans.push_back(cur);
return;
}
if(target<)return;
for(int i=level;i<candidates.size();i++)
{
if (i > level && candidates[i] == candidates[i - ])continue;// 去重
cur.push_back(candidates[i]);
dfs(i+,target-candidates[i],candidates,cur,ans);
cur.pop_back();
} }

III 简单dfs递归,限制条件是k个数其和为n

     vector<vector<int>> combinationSum3(int k, int n) {
vector<vector<int>> ans;
vector<int> cur;
dfs(k,n,,cur,ans);
return ans;
}
void dfs(int k,int n, int level, vector<int> &cur, vector<vector<int>> &ans)
{
if(k==&&n==)
{
ans.push_back(cur);
return;
}
if(k==)return;
for(int i=level;i<=;i++)
{
cur.push_back(i);
dfs(k-,n-i,i+,cur,ans);
cur.pop_back();
}
}

IV 简单dp,dfs超时,记忆化dfs应该可以

         dp[]=;
for(int i=;i<=target;i++)
{
for(int j=;j<nums.size();j++)
{
if(nums[j]<=i)dp[i]+=dp[i-nums[j]];
}
}
return dp[target];