dfs是比较简单的做法。。但总觉得会有类似的数学公式或者关系之类的
vector<vector<int>> ans;
vector<int> newsequece;
int aim;
void dfs(int sum, int i, vector<int>& temp)
{
if (sum == aim)
{
ans.push_back(temp); //以前在这儿加了一句pop,但这不能说不对,但会少考虑情况,不容易想全
return;
}
if (sum>aim)
return; //和上面情况相同,也曾加了一句pop
for (int j = i; j < newsequece.size(); j++)
{
if (sum + newsequece[j] > aim)
{
return;
}
temp.push_back(newsequece[j]);
dfs(sum + newsequece[j], j, temp);
temp.pop_back(); //在这儿加比较好
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target)
{
aim = target;
sort(candidates.begin(), candidates.end());
for (int i = 0; i < candidates.size(); i++)
if (candidates[i] <= target)
newsequece.push_back(candidates[i]);
vector<int> temp;
dfs(0, 0, temp);
return ans;
}