标签:pre 不同的 去重 can signed 个数 重复 nat target
class Solution {
public:
vector<int>tmp;
vector<vector<int>>res;
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
dfs(candidates,target,0,0);
return res;
}
void dfs(vector<int>&candidates,int target,int sum,int start)
{
if(sum==target) res.push_back(tmp);
else
{
for(int i=start;i<candidates.size();i++)
{
if(sum+candidates[i]<=target)
{
tmp.push_back(candidates[i]);
dfs(candidates,target,sum+candidates[i],i);
tmp.pop_back();
}
}
}
}
};
class Solution {
public:
vector<int>tmp;
vector<vector<int>>res;
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());//排序方便去重
dfs(candidates,target,0,0);
return res;
}
void dfs(vector<int>& candidates,int target,int sum,int start)
{
if(sum==target) res.push_back(tmp);
else
{
for(int i=start;i<candidates.size();i++)
{
if(sum+candidates[i]<=target)
{
if(i>start&&candidates[i]==candidates[i-1]) continue;
tmp.push_back(candidates[i]);
dfs(candidates,target,sum+candidates[i],i+1);
tmp.pop_back();
}
}
}
}
};
class Solution {
public:
vector<int>tmp;
vector<vector<int>>ans;
vector<vector<int>> combinationSum3(int k, int n) {
dfs(k,n,0,1);
return ans;
}
void dfs(int k,int n,int sum,int start)
{
if(sum==n&&tmp.size()==k)
ans.push_back(tmp);
else
{
for(int i=start;i<=9;i++)
{
tmp.push_back(i);
dfs(k,n,sum+i,i+1);
tmp.pop_back();
}
}
}
};
状态表示:dp[i]表示以i结尾的组合数
状态计算:dp[i+nums[i]]+=dp[i]
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
vector<unsigned long long>dp(target+1,0);
dp[0]=1;
//先枚举中间状态
for(int i=0;i<target;i++)
{
//枚举填数
for(auto num:nums)
{
if(i+num<=target)
dp[i+num]+=dp[i];
}
}
return dp[target];
}
};
标签:pre 不同的 去重 can signed 个数 重复 nat target
原文地址:https://www.cnblogs.com/Tsukinousag1/p/14678014.html