forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iterator-for-combination.py
93 lines (73 loc) · 2.42 KB
/
iterator-for-combination.py
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# Time: O(k), per operation
# Space: O(k)
import itertools
class CombinationIterator(object):
def __init__(self, characters, combinationLength):
"""
:type characters: str
:type combinationLength: int
"""
self.__it = itertools.combinations(characters, combinationLength)
self.__curr = None
self.__last = characters[-combinationLength:]
def next(self):
"""
:rtype: str
"""
self.__curr = "".join(self.__it.next())
return self.__curr
def hasNext(self):
"""
:rtype: bool
"""
return self.__curr != self.__last
# Time: O(k), per operation
# Space: O(k)
import functools
class CombinationIterator2(object):
def __init__(self, characters, combinationLength):
"""
:type characters: str
:type combinationLength: int
"""
self.__characters = characters
self.__combinationLength = combinationLength
self.__it = self.__iterative_backtracking()
self.__curr = None
self.__last = characters[-combinationLength:]
def __iterative_backtracking(self):
def conquer():
if len(curr) == self.__combinationLength:
return curr
def prev_divide(c):
curr.append(c)
def divide(i):
if len(curr) != self.__combinationLength:
for j in reversed(xrange(i, len(self.__characters)-(self.__combinationLength-len(curr)-1))):
stk.append(functools.partial(post_divide))
stk.append(functools.partial(divide, j+1))
stk.append(functools.partial(prev_divide, self.__characters[j]))
stk.append(functools.partial(conquer))
def post_divide():
curr.pop()
curr = []
stk = [functools.partial(divide, 0)]
while stk:
result = stk.pop()()
if result is not None:
yield result
def next(self):
"""
:rtype: str
"""
self.__curr = "".join(next(self.__it))
return self.__curr
def hasNext(self):
"""
:rtype: bool
"""
return self.__curr != self.__last
# Your CombinationIterator object will be instantiated and called as such:
# obj = CombinationIterator(characters, combinationLength)
# param_1 = obj.next()
# param_2 = obj.hasNext()