forked from KnowledgeCenterYoutube/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
216_Combination_Sum_III
71 lines (61 loc) · 1.91 KB
/
216_Combination_Sum_III
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
Leetcode 216: Combination Sum III
Detailed video explanation: https://youtu.be/rP_K3WJnRR4
=================================
C++:
----
class Solution {
vector<vector<int>> result;
void try_combination(vector<int>& combination, int k, int n, int start){
if(k == combination.size()){
if(n == 0) result.push_back(combination);
return;
}
for(int i = start; i <= 9; ++i){
combination.push_back(i);
try_combination(combination, k, n-i, i+1);
combination.pop_back();
}
}
public:
vector<vector<int>> combinationSum3(int k, int n) {
vector<int> combination;
try_combination(combination, k, n, 1);
return result;
}
};
Java:
-----
class Solution {
List<List<Integer>> result = new ArrayList();
void try_combination(List<Integer> combination, int k, int n, int start){
if(k == combination.size()){
if(n == 0) result.add(new ArrayList<Integer>(combination));
return;
}
for(int i = start; i <= 9; ++i){
combination.add(i);
try_combination(combination, k, n-i, i+1);
combination.remove(combination.size() - 1);
}
}
public List<List<Integer>> combinationSum3(int k, int n) {
List<Integer> combination = new ArrayList();
try_combination(combination, k, n, 1);
return result;
}
}
Python3:
-------
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
result = []
def try_combination(combination, n, start):
if k == len(combination):
if n == 0: result.append(combination.copy())
return
for i in range(start, 10):
combination.append(i)
try_combination(combination, n-i, i+1)
combination.pop()
try_combination([], n, 1)
return result