跟之前的题目都类似,这题可以不固定长度,可以重复使用
class Solution {
private:
vector<vector<int>>result;
vector<int>path;
void backtrackingf(vector<int>& candidates,int target,int sum,int startindex)
{
if(sum>target)return;//加上大于目标值,退出
if(sum==target)
{
result.push_back(path);
return;
}
for(int i=startindex;i<candidates.size();i++)
{
sum+=candidates[i];
path.push_back(candidates[i]);
backtrackingf(candidates,target,sum,i);//i意味着可以重复
sum-=candidates[i];
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
result.clear();
path.clear();
backtrackingf(candidates,target,0,0);//从数组第一个值开始
return result;
}
};