Skip to content

Commit 43b1864

Browse files
Add files via upload
1 parent e64dc72 commit 43b1864

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
class Solution
2+
{
3+
public:
4+
vector<vector<int>> combinationSum3(int k, int n)
5+
{
6+
vector<vector<int>> res;
7+
vector<int> candidate;
8+
9+
dfs(res, candidate, k, n, 1);
10+
11+
return res;
12+
}
13+
private:
14+
void dfs(vector<vector<int>>& res, vector<int>& candidate, int n, int target, int start)
15+
{
16+
if (n == 2)
17+
{
18+
int leftPtr = start;
19+
int rightPtr = 9;
20+
21+
while (leftPtr < rightPtr)
22+
{
23+
if (leftPtr + rightPtr == target)
24+
{
25+
candidate.push_back(leftPtr);
26+
candidate.push_back(rightPtr);
27+
28+
res.push_back(candidate);
29+
30+
candidate.pop_back();
31+
candidate.pop_back();
32+
33+
++leftPtr;
34+
--rightPtr;
35+
}
36+
else if (leftPtr + rightPtr > target)
37+
{
38+
--rightPtr;
39+
}
40+
else
41+
{
42+
++leftPtr;
43+
}
44+
}
45+
}
46+
else
47+
{
48+
for (int i = start; i <= 9; ++i)
49+
{
50+
candidate.push_back(i);
51+
52+
dfs(res, candidate, n - 1, target - i, i + 1);
53+
54+
candidate.pop_back();
55+
}
56+
}
57+
}
58+
};

0 commit comments

Comments
 (0)