给定一组候选数字(C)和目标数字(T),找到C中所有唯一的组合,其中候选数字总和为T.
可以从C无限次数中选择相同的重复数字。
All numbers (including target) will be positive integers. Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak). The combinations themselves must be sorted in ascending order. CombinationA > CombinationB iff (a1 > b1) OR (a1 = b1 AND a2 > b2) OR … (a1 = b1 AND a2 = b2 AND … ai = bi AND ai+1 > bi+1) The solution set must not contain duplicate combinations.
实施例,
给定候选集2,3,6,7
和目标7
,
解决方案集是:
[2, 2, 3]
[7]
解决方案代码是:
class Solution {
public:
void doWork(vector<int> &candidates, int index, vector<int> ¤t, int currentSum, int target, vector<vector<int> > &ans) {
if (currentSum > target) {
return;
}
if (currentSum == target) {
ans.push_back(current);
return;
}
for (int i = index; i < candidates.size(); i++) {
current.push_back(candidates[i]);
currentSum += candidates[i];
doWork(candidates, i, current, currentSum, target, ans);
current.pop_back();
currentSum -= candidates[i];
}
}
vector<vector<int>> combinationSum(vector<int> &candidates, int target) {
vector<int> current;
vector<vector<int> > ans;
sort(candidates.begin(), candidates.end());
vector<int> uniqueCandidates;
for (int i = 0; i < candidates.size(); i++) {
if (i == 0 || candidates[i] != candidates[i-1]) {
uniqueCandidates.push_back(candidates[i]);
}
}
doWork(uniqueCandidates, 0, current, 0, target, ans);
return ans;
}
};
现在,虽然我可以通过一个示例案例来理解解决方案,但我怎么能自己提出这样的解决方案。主要工作是这个功能:
for (int i = index; i < candidates.size(); i++) {
current.push_back(candidates[i]);
currentSum += candidates[i];
doWork(candidates, i, current, currentSum, target, ans);
current.pop_back();
currentSum -= candidates[i];
}
请告诉我如何理解上述代码以及如何思考该解决方案。我可以解决基本的递归问题,但这些问题看起来遥不可及。谢谢你的时间。
答案 0 :(得分:1)
那么代码基本上是做什么的:
为了理解递归,我想从非常简单的案例开始。让我们看看例如:
Candidates: { 2, 2, 1 }
Target: 4
对重复项进行排序和删除会将设置更改为{1,2}。递归的顺序是: