v_yanushkovsky

#leetcode 40. Задача Combination Sum II через backtracking

Jul 10th, 2026
17
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.86 KB | None | 0 0
  1.  
  2. vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
  3.     sort(candidates.begin(), candidates.end()); // сортируем массив
  4.  
  5.     vector<vector<int>> ans;
  6.     vector<int> cur;
  7.  
  8.     dfs(candidates, target, ans, cur, 0, 0);
  9.  
  10.     return ans;
  11. }
  12.  
  13. // TODO функция должна принимать ОТСОРТИРОВАННЫЙ МАССИВ candidates
  14. void dfs(vector<int>& candidates, int target, vector<vector<int>>& ans, vector<int>& cur, int curSum, int start) {
  15.     if (curSum == target) {
  16.         ans.push_back(cur);
  17.         return;
  18.     }
  19.  
  20.     if (curSum > target) {
  21.         return;
  22.     }
  23.  
  24.     for (int j = start; j < candidates.size(); ++j) {
  25.        
  26.         if (j > start && candidates[j - 1] == candidates[j]) {
  27.             continue;
  28.         }
  29.  
  30.         cur.push_back(candidates[j]);
  31.         dfs(candidates, target, ans, cur, curSum + candidates[j], j + 1);
  32.         cur.pop_back();
  33.     }
  34.  
  35.     return;
  36. }
Advertisement
Add Comment
Please, Sign In to add comment