216. Combination Sum III

LeetCode

BackTracking link

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
class Solution {
private void util(List<List<Integer>> res,List<Integer> ls,int k,int n,int start){
if(ls.size()>k) return;

if(ls.size()==k&&n==0) {
res.add(new ArrayList<>(ls));
return;
}

for(int i=start;i<=n&&i<=9;i++){
ls.add(i);
util(res,ls,k,n-i,i+1);
ls.remove(ls.size()-1);
}
}

public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> res=new ArrayList<>();
util(res,new ArrayList<Integer>(),k,n,1);
return res;
}
}
/*
class Solution {
private void util(Set<List<Integer>> set,List<Integer> ls,int k,int n){
// System.out.println(ls+","+n);
if(ls.size()==k&&n!=0) return;
if(ls.size()==k&&n==0) {
ArrayList<Integer> a_ls=new ArrayList<>(ls);
Collections.sort(a_ls);
set.add(a_ls);
}›
for(int i=1;i<=9;i++){
if(!ls.contains(i)&&ls.size()<k){
ls.add(i);
util(set,ls,k,n-i);
ls.remove(ls.size()-1);
}
}

}
public List<List<Integer>> combinationSum3(int k, int n) {
Set<List<Integer>> set=new HashSet<>();
util(set,new ArrayList<Integer>(),k,n);
List<List<Integer>> res=new ArrayList<>(set);
return res;
}
}
*/

0%