1+ // https://leetcode.com/problems/combination-sum/
2+ // Difficulty Level: Medium
3+ // Tags: Array, Backtracking
4+ // since we have to print all, and not just count or max or min, we won't use DP but backtracking
5+
6+ class Solution {
7+ public:
8+ vector<vector<int >> combinationSum (vector<int >& candidates, int target)
9+ {
10+ sort (candidates.begin (), candidates.end ());
11+
12+ // Note that we don't have duplicates in the array, else we had to delete the duplicates here bcoz
13+ // we can already take each element multiple times, so duplicate elements don't make a difference
14+
15+ int index = candidates.size ()-1 ;
16+ while (index >=0 && candidates[index] > target)
17+ {
18+ index--;
19+ }
20+
21+ vector<int > v;
22+ vector<vector<int >> res; // stores result
23+ backtrack (candidates, target, 0 , index, v, res);
24+ return res;
25+ }
26+
27+ void backtrack (vector<int > candidates, int target, int curr_sum, int index, vector<int > v, vector<vector<int >>& res)
28+ {
29+ if (curr_sum == target) // if the sum of elements of v add up to target, push v to result vector
30+ {
31+ res.push_back (v);
32+ return ;
33+ }
34+
35+ // check all the elements <= target - curr_sum
36+ for (int i=index; i>=0 ; i--)
37+ {
38+ curr_sum += candidates[i];
39+
40+ if (curr_sum > target) // don't include the element if sum is exceeding the target
41+ {
42+ curr_sum -= candidates[i];
43+ continue ;
44+ }
45+ v.push_back (candidates[i]);
46+
47+ // backtrack to find rest of the elements of v
48+ // note that we have passed 'i' and not 'i+1' since we could include the same element any no. of times
49+ backtrack (candidates, target, curr_sum, i, v, res);
50+
51+ curr_sum -= candidates[i];
52+ v.pop_back ();
53+ }
54+ }
55+ };
0 commit comments