zoukankan      html  css  js  c++  java
  • 【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()
  • 相关阅读:
    ES6之模块化
    ES6之展开运算符
    ES6之解构赋值
    ES6之对象的语法糖
    ES6之函数的语法糖
    ES6之模板字符串
    Exchanger详解
    DNS解析过程
    CyclicBarrier详解
    ConuntDownLatch详解
  • 原文地址:https://www.cnblogs.com/seyjs/p/12041872.html
Copyright © 2011-2022 走看看