-
Notifications
You must be signed in to change notification settings - Fork 286
Expand file tree
/
Copy pathCombinationSumIIIA.java
More file actions
30 lines (27 loc) · 898 Bytes
/
CombinationSumIIIA.java
File metadata and controls
30 lines (27 loc) · 898 Bytes
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
class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
Set<List<Integer>> set = new HashSet<>();
combinationSum3Helper(set, k, n, new HashSet<>());
return new ArrayList<>(set);
}
private void combinationSum3Helper(Set<List<Integer>> ans, int noOfElements, int remainingSum, Set<Integer> runningSet) {
if(noOfElements ==0){
if(remainingSum==0){
ans.add(new ArrayList<>(runningSet));
return ;
} else {
return ;
}
}
if(remainingSum<0){
return ;
}
for(int i=1;i<=9;i++) {
if(!runningSet.contains(i)){
runningSet.add(i);
combinationSum3Helper(ans,noOfElements-1, remainingSum- i, runningSet);
runningSet.remove(i);
}
}
}
}