• leetcode 1286. Iterator for Combination


    Design an Iterator class, which has:

    • A constructor that takes a string characters of sorted distinctlowercase 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.

    python3:利用itertools.combinations模块

     1 class CombinationIterator:
     2 
     3     def __init__(self, A: str, k: int):
     4         self.it = itertools.combinations(A, k)
     5         self.last = A[-k:]
     6         self.res = ""
     7         
     8 
     9     def next(self) -> str:
    10         self.res = ''.join(next(self.it))
    11         return self.res
    12 
    13     def hasNext(self) -> bool:
    14         return self.res != self.last

    C++:先产生所有符合字典序的子字符串。(回溯法)

     1 class CombinationIterator {
     2 private:
     3     queue<string> iterator;
     4     void combinationIterator(const string &characters, const int &combinationLength, int startpos, string &oneInstance, queue<string> &resultQueue) {
     5         if (oneInstance.length() == combinationLength) {
     6             resultQueue.push(oneInstance);
     7             return;
     8         }
     9         for (int i = startpos; i < characters.length(); ++i) {
    10             oneInstance.push_back(characters[i]);
    11             combinationIterator(characters, combinationLength, i + 1, oneInstance, resultQueue);
    12             oneInstance.pop_back();
    13         }
    14     }
    15 public:
    16     CombinationIterator(string characters, int combinationLength) {
    17         string oneInstance = "";
    18         combinationIterator(characters, combinationLength, 0, oneInstance, iterator);
    19     }
    20     
    21     string next() {
    22         string ans = "";
    23         if (hasNext()) {
    24             ans = iterator.front();
    25             iterator.pop();
    26         }
    27         return ans;
    28     }
    29     
    30     bool hasNext() {
    31         //队列非空,说明还有
    32         return !iterator.empty();
    33     }
    34 };
  • 相关阅读:
    【Java】快速排序、归并排序、堆排序、基数排序实现总结
    【Java】二分查找、插值查找、斐波那契查找的实现,及分析
    【Java】Java实现常见的七种排序
    【C】常见的排序
    栈,迷宫问题
    海量数据处理问题
    【C】 布隆过滤器BloomFilter
    哈希变形---位图
    C实现Hash表,链式结构
    C实现Hash表,开放定址法
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/12169958.html
Copyright © 2020-2023  润新知