Combination Sum III LeetCode solution in C++

1
class Solution {
2
public:
3
vector<vector<int>> ans;
4
// declare temp global vector in this vector we will store temprary
5
// combinations
6
vector<int> temp;
7
void solve(int k, int n, int order) {
8
// check if our target became zero and combination size became zero then
9
// push temp vector inside the ans it means this temp vector combination
10
// having sum is equal to target and size of vector is equal to k
11
if (n == 0 && k == 0) {
12
ans.push_back(temp);
13
return;
14
}
15
// check if our target is less than zero then return
16
if (n < 0) return;
17
// take for loop and check for all posibility ahead of order
18
for (int i = order; i <= 9; i++) {
19
// push current index value
20
temp.push_back(i);
21
// call solve function for further posiblity
22
solve(k - 1, n - i, i + 1);
23
// Pop last push value
24
temp.pop_back();
25
}
26
}
27
vector<vector<int>> combinationSum3(int k, int n) {
28
solve(k, n, 1);
29
return ans;
30
}
31
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0