forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombinations.java
More file actions
executable file
·34 lines (29 loc) · 1.02 KB
/
combinations.java
File metadata and controls
executable file
·34 lines (29 loc) · 1.02 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
public class Solution {
public ArrayList<ArrayList<Integer>> combine(int n, int k) {
// Start typing your Java solution below
// DO NOT write main() function
Stack<ArrayList<Integer>> now = new Stack<ArrayList<Integer>>();
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
for(int i=1;i<n+1;i++){
ArrayList<Integer> al =new ArrayList<Integer>();
al.add(i);
now.push(al);
}
while(!now.isEmpty()){
ArrayList<Integer> top = now.pop();
int last = top.get(top.size()-1);
if(top.size()==k ) {
res.add(top);
continue;
}
for(int i=last+1;i<n+1;i++){
if(n-i>=k-top.size()-1){
ArrayList<Integer> tmp = new ArrayList<Integer>(top);
tmp.add(i);
now.push(tmp);
}
}
}
return res;
}
}