Approach
Depth-first search
For Iterator for Combination, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 78 lines of C++ from the credited upstream file iterator-for-combination.cpp.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4class CombinationIterator {5public:6 CombinationIterator(string characters, int combinationLength)7 : characters_(characters)8 , combinationLength_(combinationLength)9 , last_(prev(characters.cend(), combinationLength), characters.cend())10 , stk_{bind(&CombinationIterator::divide, this, 0)} {11 12 }13 14 string next() {15 iterative_backtracking();16 return curr_;17 }18 19 bool hasNext() {20 return curr_ != last_;21 }22 23private:24 void iterative_backtracking() {25 while (!stk_.empty()) {26 const auto cb = move(stk_.back());27 stk_.pop_back();28 if (cb()) {29 return;30 }31 }32 }33 34 bool conquer() {35 if (curr_.length() == combinationLength_) {36 return true;37 }38 return false;39 }40 41 bool prev_divide(char c) {42 curr_.push_back(c);43 return false;44 }45 46 bool divide(int i) {47 if (curr_.length() != combinationLength_) {48 for (int j = int(characters_.length()) - (combinationLength_ - int(curr_.length()) - 1) - 1;49 j >= i; --j) {50 stk_.emplace_back(bind(&CombinationIterator::post_divide, this));51 stk_.emplace_back(bind(&CombinationIterator::divide, this, j + 1));52 stk_.emplace_back(bind(&CombinationIterator::prev_divide, this, characters_[j]));53 }54 }55 stk_.emplace_back(bind(&CombinationIterator::conquer, this));56 return false;57 }58 59 bool post_divide() {60 curr_.pop_back();61 return false;62 }63 64 const string characters_;65 const int combinationLength_;66 string curr_;67 string last_;68 vector<function<bool()>> stk_;69};70 71/**72 * Your CombinationIterator object will be instantiated and called as such:73 * CombinationIterator* obj = new CombinationIterator(characters, combinationLength);74 * string param_1 = obj->next();75 * bool param_2 = obj->hasNext();76 */77 78