forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path_1286.java
51 lines (44 loc) · 1.7 KB
/
_1286.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
45
46
47
48
49
50
51
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.List;
public class _1286 {
public static class Solution1 {
public static class CombinationIterator {
List<String> list;
int index;
int combinationLength;
boolean[] visited;
public CombinationIterator(String characters, int combinationLength) {
this.index = 0;
this.list = new ArrayList<>();
this.combinationLength = combinationLength;
this.visited = new boolean[characters.length()];
buildAllCombinations(characters, 0, new StringBuilder(), visited);
}
private void buildAllCombinations(String characters, int start, StringBuilder sb, boolean[] visited) {
if (sb.length() == combinationLength) {
list.add(sb.toString());
return;
} else {
for (int i = start; i < characters.length(); ) {
if (!visited[i]) {
sb.append(characters.charAt(i));
visited[i] = true;
buildAllCombinations(characters, i++, sb, visited);
visited[i - 1] = false;
sb.setLength(sb.length() - 1);
} else {
i++;
}
}
}
}
public String next() {
return list.get(index++);
}
public boolean hasNext() {
return index < list.size();
}
}
}
}