File tree 1 file changed +23
-15
lines changed
scripts/algorithms/I/Iterator for Combination
1 file changed +23
-15
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime : 54 ms (Top 68.38 % ) | Memory : 20.00 MB (Top 5.53 % )
2
+
1
3
class CombinationIterator :
2
4
3
5
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
+
16
11
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
19
18
20
19
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
You can’t perform that action at this time.
0 commit comments