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 };

 

posted @ 2020-01-09 10:19  琴影  阅读(460)  评论(0编辑  收藏  举报