forked from lennylxx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
216.cpp
48 lines (39 loc) · 1.03 KB
/
216.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int> > combinationSum3(int k, int n) {
vector<vector<int> > ans;
vector<int> temp;
combinationSum3Helper(1, n, k, temp, ans);
return ans;
}
void combinationSum3Helper(int start, int n, int k, vector<int> &temp, vector<vector<int> > &ans) {
if (k == temp.size() && n == 0) {
ans.push_back(temp);
return;
}
else if (temp.size() > k || n < 0) {
return;
}
for (int i = start; i <= 9; i++) {
temp.push_back(i);
combinationSum3Helper(i + 1, n - i, k, temp, ans);
temp.pop_back();
}
}
};
int main() {
int k = 3;
int n = 7;
Solution s;
vector<vector<int> > ans = s.combinationSum3(k, n);
for (int i = 0; i < ans.size(); i++) {
for (int j = 0; j < ans[i].size(); j++) {
printf("%d ", ans[i][j]);
}
printf("\n");
}
return 0;
}