Skip to content

Commit 15bf06c

Browse files
committed
basics
1 parent 710c1e0 commit 15bf06c

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

src/Combinations/Solution.java

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package Combinations;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
/**
7+
* User: Danyang
8+
* Date: 1/24/2015
9+
* Time: 11:05
10+
*
11+
* Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
12+
13+
For example,
14+
If n = 4 and k = 2, a solution is:
15+
16+
[
17+
[2,4],
18+
[3,4],
19+
[2,3],
20+
[1,2],
21+
[1,3],
22+
[1,4],
23+
]
24+
*/
25+
public class Solution {
26+
/**
27+
* Notice:
28+
* 1. debug recursive
29+
* @param n
30+
* @param k
31+
* @return
32+
*/
33+
public List<List<Integer>> combine(int n, int k) {
34+
List<List<Integer>> ret = new ArrayList<>();
35+
dfs(n, k, 1, new ArrayList<>(), ret);
36+
return ret;
37+
}
38+
39+
void dfs(int n, int k, int next, List<Integer> cur, List<List<Integer>> ret) {
40+
if(cur.size()>k)
41+
return ;
42+
if(cur.size()==k) {
43+
ret.add(new ArrayList<>(cur));
44+
return ;
45+
}
46+
for(int i=next; i<=n; i++) {
47+
cur.add(i);
48+
dfs(n, k, i+1, cur, ret);
49+
cur.remove(cur.size()-1);
50+
}
51+
}
52+
53+
public static void main(String[] args) {
54+
List<List<Integer>> ret = new Solution().combine(4, 2);
55+
System.out.println(ret);
56+
}
57+
}

0 commit comments

Comments
 (0)