Skip to content

Commit 7ae3abb

Browse files
committed
Runtime: 54 ms (Top 68.38%) | Memory: 20.00 MB (Top 5.53%)
1 parent 7d6f049 commit 7ae3abb

File tree

1 file changed

+23
-15
lines changed

1 file changed

+23
-15
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,29 @@
1+
// Runtime: 54 ms (Top 68.38%) | Memory: 20.00 MB (Top 5.53%)
2+
13
class CombinationIterator:
24

35
def __init__(self, characters: str, combinationLength: int):
4-
res = []
5-
def dfs(low, path):
6-
if len(path) == combinationLength:
7-
res.append(path)
8-
return
9-
for idx in range(low, len(characters)):
10-
dfs(idx+1, path+characters[idx])
11-
12-
dfs(0, "")
13-
self.combinations = res
14-
self.currIdx = 0
15-
6+
self.characters = characters
7+
self.n = len(characters)
8+
self.combinations = gen_combinations(self.n, combinationLength)
9+
self.ind = len(self.combinations) - 1
10+
1611
def next(self) -> str:
17-
self.currIdx += 1
18-
return self.combinations[self.currIdx-1]
12+
s = ""
13+
for i in range(self.n):
14+
if self.combinations[self.ind][i] != "0":
15+
s += self.characters[i]
16+
self.ind -= 1
17+
return s
1918

2019
def hasNext(self) -> bool:
21-
return self.currIdx <= len(self.combinations) - 1
20+
return self.ind > -1
21+
22+
def gen_combinations(l, n):
23+
end = int("1" * l, 2)
24+
ans = []
25+
for i in range(end + 1):
26+
b = bin(i)[2:]
27+
if b.count('1') == n:
28+
ans.append(b.zfill(l))
29+
return ans

0 commit comments

Comments
 (0)