-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombinationSum3.java
More file actions
51 lines (45 loc) · 1.35 KB
/
combinationSum3.java
File metadata and controls
51 lines (45 loc) · 1.35 KB
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
import java.util.ArrayList;
import java.util.List;
/**
* Author : WindAsMe
* File : combinationSum3.java
* Time : Create on 18-6-6
* Location : ../Home/JavaForLeeCode2/combinationSum3.java
* Function : LeeCode No.216
*/
public class combinationSum3 {
private static List<List<Integer>> ans = new ArrayList<>();
private static int[] paths = new int[100];
private static void robot(int index, int k, int n, int j) {
if (index >= k) {
List<Integer> temp = new ArrayList<>();
int sum = 0;
for(int i = 0; i < k; i++) {
sum += paths[i];
temp.add(paths[i]);
}
if (sum == n) {
ans.add(temp);
}
return;
}
for(int i = j; i <= 9; i++) {
paths[index] = i;
robot(index + 1, k, n, i+1);
}
}
private static List<List<Integer>> combinationSum3Result(int k, int n) {
ans.clear();
robot(0, k, n, 1);
return ans;
}
public static void main(String[] args) {
List<List<Integer>> lists = combinationSum3Result(3, 7);
for (List<Integer> list : lists) {
for (int j = 0; j < 3; j++) {
System.out.print(list.get(j) + " ");
}
System.out.println();
}
}
}