描述
求和为目标值的组合数
解决
与用DP求一共有多少种组合的题目类似
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> res;
vector<int> tmp;
int length = candidates.size();
func(candidates, target, res, tmp, length, 0);
return res;
}
void func(vector<int>& candidates, int target, vector<vector<int>>& res, vector<int>& tmp, int& length, int pos)
{
if (target == 0)
{
res.push_back(tmp);
return ;
}
for (int i = pos; i < length; ++i)
{
if (target >= candidates[i])
{
tmp.push_back(candidates[i]);
func(candidates, target - candidates[i], res, tmp, length, i);
tmp.pop_back();
}
}
return ;
}
};