|
| 1 | +Design an Iterator class, which has: |
| 2 | + |
| 3 | +A constructor that takes a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments. |
| 4 | +A function next() that returns the next combination of length combinationLength in lexicographical order. |
| 5 | +A function hasNext() that returns True if and only if there exists a next combination. |
| 6 | + |
| 7 | + |
| 8 | +Example: |
| 9 | + |
| 10 | +CombinationIterator iterator = new CombinationIterator("abc", 2); // creates the iterator. |
| 11 | + |
| 12 | +iterator.next(); // returns "ab" |
| 13 | +iterator.hasNext(); // returns true |
| 14 | +iterator.next(); // returns "ac" |
| 15 | +iterator.hasNext(); // returns true |
| 16 | +iterator.next(); // returns "bc" |
| 17 | +iterator.hasNext(); // returns false |
| 18 | + |
| 19 | + |
| 20 | +Constraints: |
| 21 | + |
| 22 | +1 <= combinationLength <= characters.length <= 15 |
| 23 | +There will be at most 10^4 function calls per test. |
| 24 | +It's guaranteed that all calls of the function next are valid. |
| 25 | + Hide Hint #1 |
| 26 | +Generate all combinations as a preprocessing. |
| 27 | + Hide Hint #2 |
| 28 | +Use bit masking to generate all the combinations. |
| 29 | +
|
| 30 | +
|
| 31 | +
|
| 32 | +
|
| 33 | +
|
| 34 | +
|
| 35 | +
|
| 36 | +
|
| 37 | +
|
| 38 | +
|
| 39 | +
|
| 40 | +
|
| 41 | +class CombinationIterator { |
| 42 | +public: |
| 43 | + queue<string> q; |
| 44 | +
|
| 45 | + void allCombinations(string characters, int k, int s, string str){ |
| 46 | + if(k==0){ |
| 47 | + q.push(str); |
| 48 | + return; |
| 49 | + } |
| 50 | + for(int i=s; i<characters.length();i++){ |
| 51 | + str+=characters[i]; |
| 52 | + allCombinations(characters, k-1, i+1, str); |
| 53 | + str.erase(str.end()-1); |
| 54 | + } |
| 55 | + } |
| 56 | +
|
| 57 | + CombinationIterator(string characters, int combinationLength) { |
| 58 | + string str=""; |
| 59 | + allCombinations(characters, combinationLength, 0, str); // <characters, combinationLength, start, str> |
| 60 | + } |
| 61 | +
|
| 62 | + string next() { |
| 63 | + string next = q.front(); |
| 64 | + q.pop(); |
| 65 | + return next; |
| 66 | + } |
| 67 | +
|
| 68 | + bool hasNext() { |
| 69 | + return !q.empty(); |
| 70 | + } |
| 71 | +}; |
| 72 | +
|
| 73 | +/** |
| 74 | + * Your CombinationIterator object will be instantiated and called as such: |
| 75 | + * CombinationIterator* obj = new CombinationIterator(characters, combinationLength); |
| 76 | + * string param_1 = obj->next(); |
| 77 | + * bool param_2 = obj->hasNext(); |
| 78 | + */ |
0 commit comments