this problem is a little hard.
we can use the dfs to solve this problem.
when you push_back a num and if the sum is still not enough we can push another
if it overflow we just return.1
其实中间的那段代码可以这么理解,无论对于什么情况,我们都要把当前的放进去然后继续跑这个函数,实在不行就放下一个!也就是那个for循环。我们要尽量把每一个都放进去试一试。对,大概就是这样吧。
class Solution {
public:
void getCombineSum(
int &sum,
int level,
int target,
vector<int> &solution,
vector<int> &candidates,
vector<vector<int>> &result
){
if(sum > target)
return ;
if(sum == target)
result.push_back(solution);
if(sum < target)
{
for(int i = level;i<candidates.size();i++)
{
sum += candidates[i];
solution.push_back(candidates[i]);
getCombineSum(sum,i,target,solution,candidates,result);
solution.pop_back();
sum -= candidates[i];
}
}
}
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
vector<int> solution;
vector<vector<int>> result;
int sum = 0;
sort(candidates.begin(),candidates.end());
getCombineSum(sum,0,target,solution,candidates,result);
return result;
}
};