forked from algorhythms/LeetCode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
57 lines (51 loc) · 1.15 KB
/
Copy pathSolution.java
File metadata and controls
57 lines (51 loc) · 1.15 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
52
53
54
55
56
57
package Combinations;
import java.util.ArrayList;
import java.util.List;
/**
* User: Danyang
* Date: 1/24/2015
* Time: 11:05
*
* Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
*/
public class Solution {
/**
* Notice:
* 1. debug recursive
* @param n
* @param k
* @return
*/
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> ret = new ArrayList<>();
dfs(n, k, 1, new ArrayList<>(), ret);
return ret;
}
void dfs(int n, int k, int next, List<Integer> cur, List<List<Integer>> ret) {
if(cur.size()>k)
return ;
if(cur.size()==k) {
ret.add(new ArrayList<>(cur));
return ;
}
for(int i=next; i<=n; i++) {
cur.add(i);
dfs(n, k, i+1, cur, ret);
cur.remove(cur.size()-1);
}
}
public static void main(String[] args) {
List<List<Integer>> ret = new Solution().combine(4, 2);
System.out.println(ret);
}
}