leetcode1286. Iterator for Combination

Posted seyjs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode1286. Iterator for Combination相关的知识,希望对你有一定的参考价值。

题目如下:

Design an Iterator class, which has:

  • A constructor that takes a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments.
  • A function next() that returns the next combination of length combinationLength in lexicographical order.
  • A function hasNext() that returns True if and only if there exists a next combination.

Example:

CombinationIterator iterator = new CombinationIterator("abc", 2); // creates the iterator.

iterator.next(); // returns "ab"
iterator.hasNext(); // returns true
iterator.next(); // returns "ac"
iterator.hasNext(); // returns true
iterator.next(); // returns "bc"
iterator.hasNext(); // returns false

Constraints:

  • 1 <= combinationLength <= characters.length <= 15
  • There will be at most 10^4 function calls per test.
  • It‘s guaranteed that all calls of the function next are valid.

解题思路:全排列的问题,把所有排列预先计算出来即可。

代码 如下:

class CombinationIterator(object):

    def __init__(self, characters, combinationLength):
        """
        :type characters: str
        :type combinationLength: int
        """
        self.val = []
        from itertools import combinations
        for i in combinations(characters, combinationLength):
            self.val.append(‘‘.join(i))

    def next(self):
        """
        :rtype: str
        """
        return self.val.pop(0)
        

    def hasNext(self):
        """
        :rtype: bool
        """
        return len(self.val) > 0
        


# Your CombinationIterator object will be instantiated and called as such:
# obj = CombinationIterator(characters, combinationLength)
# param_1 = obj.next()
# param_2 = obj.hasNext()

 

以上是关于leetcode1286. Iterator for Combination的主要内容,如果未能解决你的问题,请参考以下文章

leetcode1286

leetcode-15双周赛-1286-字母组合迭代器

LeetCode Zigzag Iterator

LeetCode284. Peeking Iterator

LeetCode 284. Peeking Iterator

Binary Search Tree Iterator leetcode