class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> ans;
vector<int> item;
int now=0;
dfs(0,ans,item,now,target,candidates);
return ans;
}
void dfs(int layor,vector<vector<int>>&ans,vector<int>&item,int&now,int target,vector<int>& candidates)
{
if(now>target)
return;
//剪枝
if(ans.size()==149)
return;
if(layor>=candidates.size())
{
if(now==target)
{
ans.push_back(item);
}
return;
}
//超过范围,返回
dfs(layor+1,ans,item,now,target,candidates);
int t=target/candidates[layor];
for(int i=1;i<=t;i++)
{
for(int j=1;j<=i;j++)
{
item.push_back(candidates[layor]);
}
now+=i*candidates[layor];
dfs(layor+1,ans,item,now,target,candidates);
now-=i*candidates[layor];
for(int j=1;j<=i;j++)
{
item.pop_back();
}
}
//往里面凑数字~
}
};
LeetCode 39
最新推荐文章于 2024-08-23 01:05:03 发布