TGViewer
C/C++ | LeetCode C/C++ | LeetCode @easy_c_plus_task · 3.23K subscribers
Post #2134 249
Задача: 40. Combination Sum II
Сложность: medium

Дан массив candidates и число target. Найдите все уникальные комбинации, где сумма элементов равна target. Каждое число можно использовать только один раз.

Пример:
Input: candidates = [10,1,2,7,6,1,5], target = 8 Output: [[1,1,6],[1,2,5],[1,7],[2,6]]

👨‍💻 Алгоритм:

1⃣Отсортировать и подсчитать количество каждого уникального элемента, чтобы избежать дубликатов.

2⃣Запустить рекурсивный backtrack, на каждом шаге выбирая доступный элемент, уменьшая его частоту и остаток target.

3⃣Если remain == 0 — сохранить комбинацию; иначе — откатить шаг (уменьшение глубины, восстановление частоты и удаление элемента из комбинации).

😎 Решение:
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int>> results;
vector<int> comb;
map<int, int> counter;
for (int candidate : candidates) {
counter[candidate]++;
}
vector<pair<int, int>> counterList(counter.begin(), counter.end());
backtrack(comb, target, 0, counterList, results);
return results;
}

private:
void backtrack(vector<int>& comb, int remain, int curr,
vector<pair<int, int>>& counter,
vector<vector<int>>& results) {
if (remain == 0) {
results.push_back(comb);
return;
} else if (remain < 0) {
return;
}

for (int nextCurr = curr; nextCurr < counter.size(); ++nextCurr) {
auto& [candidate, freq] = counter[nextCurr];
if (freq == 0) continue;

comb.push_back(candidate);
--freq;

backtrack(comb, remain - candidate, nextCurr, counter, results);

++freq;
comb.pop_back();
}
}
};


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_c_plus_task
  1. Oct 9, 2026Задача: 33. Search in Rotated Sorted Array Сложность: medium Дан массив nums, отсортирован…
  2. Oct 7, 2026🔥 Скрытые вакансии с удаленной работой для C/C++ разработчика, которые нигде больше не пу…
  3. Oct 5, 2026Задача: 1014. Best Sightseeing Pair Сложность: easy Вам дан целочисленный массив values, в…
  4. Oct 4, 2026Задача: 1034. Coloring A Border Сложность: medium Вам дана целочисленная матричная сетка m…
  5. Oct 4, 2026Задача: 527. Word Abbreviation Сложность: hard Дано массив уникальных строк words, верните…
  6. Oct 3, 2026Задача: 952. Largest Component Size by Common Factor Сложность: hard Для бинарного дерева…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →