Skip to content

Commit ba2c250

Browse files
authored
Create CombinationSumIII.java
1 parent e8d9544 commit ba2c250

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

Backtracking/CombinationSumIII.java

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
//LeetCode 216. Combination Sum III
2+
//Question - https://leetcode.com/problems/combination-sum-iii/
3+
4+
class Solution {
5+
//k ==> size of each combination
6+
//n ==> target sum of each combination
7+
//numbers from [1..9] can be used only once.
8+
9+
public List<List<Integer>> combinationSum3(int k, int n) {
10+
List<List<Integer>> res = new ArrayList<>();
11+
helper(k, n, 1, 0, new ArrayList<>(), res);
12+
13+
return res;
14+
}
15+
16+
public void helper(int k, int n, int num, int sum, List<Integer> l, List<List<Integer>> res){
17+
//Check for the base condition
18+
if(l.size() == k && sum == n){
19+
res.add(new ArrayList<>(l));
20+
return;
21+
}
22+
23+
//to avoid useless recursion
24+
else if(l.size() == k || sum > n) return;
25+
26+
for(int i = num ; i <= 9 ; i++){
27+
//make a decision
28+
l.add(i);
29+
30+
helper(k, n, i + 1, sum + i, l, res);
31+
32+
//backtrack
33+
l.remove(l.size()-1);
34+
}
35+
}
36+
}

0 commit comments

Comments
 (0)