forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
44 lines (39 loc) · 1.13 KB
/
Solution.java
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
class CombinationIterator {
private int n;
private int combinationLength;
private String characters;
private StringBuilder t = new StringBuilder();
private List<String> cs = new ArrayList<>();
private int idx = 0;
public CombinationIterator(String characters, int combinationLength) {
n = characters.length();
this.combinationLength = combinationLength;
this.characters = characters;
dfs(0);
}
public String next() {
return cs.get(idx++);
}
public boolean hasNext() {
return idx < cs.size();
}
private void dfs(int i) {
if (t.length() == combinationLength) {
cs.add(t.toString());
return;
}
if (i == n) {
return;
}
t.append(characters.charAt(i));
dfs(i + 1);
t.deleteCharAt(t.length() - 1);
dfs(i + 1);
}
}
/**
* Your CombinationIterator object will be instantiated and called as such:
* CombinationIterator obj = new CombinationIterator(characters, combinationLength);
* String param_1 = obj.next();
* boolean param_2 = obj.hasNext();
*/