其他分享
首页 > 其他分享> > 【leetcode】1286. Iterator for Combination

【leetcode】1286. 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()

 

标签:1286,hasNext,Combination,iterator,self,next,returns,combinationLength,leetcode
来源: https://www.cnblogs.com/seyjs/p/12041872.html