Description
Design the CombinationIterator class:
CombinationIterator(string characters, int combinationLength)Initializes the object with a stringcharactersof sorted distinct lowercase English letters and a numbercombinationLengthas arguments.next()Returns the next combination of lengthcombinationLengthin lexicographical order.hasNext()Returnstrueif and only if there exists a next combination.
Β
Example 1:
Input
["CombinationIterator", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
[["abc", 2], [], [], [], [], [], []]
Output
[null, "ab", true, "ac", true, "bc", false]
Explanation
CombinationIterator itr = new CombinationIterator("abc", 2);
itr.next(); // return "ab"
itr.hasNext(); // return True
itr.next(); // return "ac"
itr.hasNext(); // return True
itr.next(); // return "bc"
itr.hasNext(); // return False
Β
Constraints:
1 <= combinationLength <= characters.length <= 15- All the characters of
charactersare unique. - At most
104calls will be made tonextandhasNext. - It is guaranteed that all calls of the function
nextare valid.
Solution
Python3
class CombinationIterator:
def __init__(self, characters: str, combinationLength: int):
self.perms = []
self.n = len(characters)
self.k = combinationLength
self.index = 0
def go(i, curr):
if len(curr) == self.k:
self.perms.append(curr)
if i == self.n:
return
for j in range(i, self.n):
go(j + 1, curr + characters[j])
go(0, '')
def next(self) -> str:
res = self.perms[self.index]
self.index += 1
return res
def hasNext(self) -> bool:
return self.index < len(self.perms)
# Your CombinationIterator object will be instantiated and called as such:
# obj = CombinationIterator(characters, combinationLength)
# param_1 = obj.next()
# param_2 = obj.hasNext()