给定一组候选数(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];
}
请告诉我如何理解上述代码以及如何去思考这个解决方案。我可以解决基本的递归问题,但这些看起来遥不可及。谢谢你的时间。
为什么我会得到downvotes? – Gyanshu
你很可能会收到降薪,因为人们觉得你要求别人为你做你的工作,而不是向你已经试图解决的问题寻求帮助。 –
@MikelF我给了这个问题至少6小时。我不知道“尝试”的定义是什么? – Gyanshu