LeetCode 5123. letter combinations iterator Iterator for Combination

Address  https://leetcode-cn.com/contest/biweekly-contest-15/problems/iterator-for-combination/

Title Description
you design an iterator class, including the following:

A constructor function, the input parameters comprising: a unique character string of ordered and characters (the string contains only lowercase letters) and a digital combinationLength.
Function next (), returns the length of a lexicographical ordering for the next letter of the combination combinationLength.
The hasNext function (), only the presence of the length of the next letter combination combinationLength, returns True; otherwise, return False.

Example:

Iterator CombinationIterator = new new CombinationIterator ( " abc " , 2 ); // create an iterator Iterator 

iterator.next (); // returns "ab" 
iterator.hasNext (); // return to true 
iterator.next (); // returns "AC" 
iterator.hasNext (); // return to true 
iterator.next (); // returns "bc" 
iterator.hasNext (); // returns false
prompt:

. 1 <= combinationLength <= characters.length <= 15 
Each test contains up to 10 ^ 4 times a function is called.
We are entitled to ensure the presence of a combination of letters each time the function next call.

 

Algorithm 1
My understanding is probably Mr. DFS to use it in various combinations vector memory
and then come back next hasnext respond to inquiries very simple

C ++ code

 1 class CombinationIterator {
 2 public:
 3     int idx = 0;
 4     vector<string> vstr;
 5     vector<char> ele;
 6     void dfs(const string& s, int len, int idx)
 7     {
 8         if (ele.size() == len) {
 9             string str(ele.begin(), ele.end());
10             vstr.push_back(str);
11             return;
12         }
13         else if (idx == s.size()) {
14             return;
15         }
16 
17         ele.push_back(s[idx]);
18         dfs(s, len, idx + 1);
19         ele.pop_back();
20 
21         dfs(s, len, idx + 1);
22     }
23 
24     CombinationIterator(string characters, int combinationLength) {
25         dfs(characters,combinationLength,0); 
26         idx = 0;
27     }
28 
29     string next() {
30         return vstr[idx++];
31     }
32 
33     bool hasNext() {
34         if(idx < vstr.size())
35             return true;
36 
37         return false;
38     }
39 };
40 
41 /**
42  * Your CombinationIterator object will be instantiated and called as such:
43 Obj = new new CombinationIterator * * CombinationIterator (characters, combinationLength);
 44 is  * String PARAM_1 = obj-> Next ();
 45  * = BOOL PARAM_2 obj-> the hasNext ();
 46 is   * / 
47  
48  OF: defddr
 49 links: https: // www.acwing.com/solution/LeetCode/content/7022/ 
50  source: AcWing
 51 copyright reserved by the authors. Commercial reprint please contact the author authorized, non-commercial reprint please indicate the source.
View Code

 

Guess you like

Origin www.cnblogs.com/itdef/p/12041651.html