Учитывая набор чисел кандидатов (С) и целевым номером (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
Скорее всего, вы получаете downvotes, потому что люди чувствуют, что вы просите других сделать вашу работу за вас, вместо того, чтобы просить о помощи в том, что вы уже пытались решить. –
@ MikelF Я дал по крайней мере 6 часов на эту проблему. Я не знаю, что такое определение «попытка»? – Gyanshu