4
4
import java .util .ArrayList ;
5
5
import java .util .List ;
6
6
7
- /**Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
7
+ /**
8
+ * 77. Combinations
9
+ *
10
+ * Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
8
11
9
12
For example,
10
13
If n = 4 and k = 2, a solution is:
16
19
[1,2],
17
20
[1,3],
18
21
[1,4],
19
- ]*/
22
+ ]
23
+ */
24
+
20
25
public class _77 {
26
+
21
27
public List <List <Integer >> combine (int n , int k ) {
22
28
List <List <Integer >> result = new ArrayList ();
23
29
int [] nums = new int [n ];
@@ -28,15 +34,14 @@ public List<List<Integer>> combine(int n, int k) {
28
34
return result ;
29
35
}
30
36
31
- void backtracking (int k , int start , int [] nums , List <Integer > temp , List <List <Integer >> result ) {
32
- if (temp .size () == k ) {
33
- List <Integer > newTemp = new ArrayList (temp );
34
- result .add (newTemp );
35
- } else if (temp .size () < k ) {
37
+ void backtracking (int k , int start , int [] nums , List <Integer > curr , List <List <Integer >> result ) {
38
+ if (curr .size () == k ) {
39
+ result .add (new ArrayList (curr ));
40
+ } else if (curr .size () < k ) {
36
41
for (int i = start ; i < nums .length ; i ++) {
37
- temp .add (nums [i ]);
38
- backtracking (k , i + 1 , nums , temp , result );
39
- temp .remove (temp .size () - 1 );
42
+ curr .add (nums [i ]);
43
+ backtracking (k , i + 1 , nums , curr , result );
44
+ curr .remove (curr .size () - 1 );
40
45
}
41
46
}
42
47
}
0 commit comments