Iterator for Combination

Tags : array, string, backtracking, leetcode, cpp, medium

Design the CombinationIterator class:

Examples #

Example 1:

Input
["CombinationIterator", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
[["abc", 2], [], [], [], [], [], []]
Output
[null, "ab", true, "ac", true, "bc", false]

Explanation
CombinationIterator itr = new CombinationIterator("abc", 2);
itr.next();    // return "ab"
itr.hasNext(); // return True
itr.next();    // return "ac"
itr.hasNext(); // return True
itr.next();    // return "bc"
itr.hasNext(); // return False

Constraints #

Solutions #

class CombinationIterator {
public:
    vector<string> v;
    string s = "";
    int k, it=0 ;
    void bt(string c, int i){
      if(s.size() == k) {
        v.push_back(s);
        return;
      }
      for(int j=i; j<c.size(); j++){
        s.push_back(c[j]);
        bt(c, j+1);
        s.pop_back();
      }
    }
    CombinationIterator(string characters, int combinationLength) {
      k = combinationLength;
      bt(characters, 0);
    }
    
    string next() {
      return v[it++];
    }
    
    bool hasNext() {
        return it < v.size();
    }
};

/**
 * Your CombinationIterator object will be instantiated and called as such:
 * CombinationIterator* obj = new CombinationIterator(characters, combinationLength);
 * string param_1 = obj->next();
 * bool param_2 = obj->hasNext();
 */