Posted on

Description

Submission

class CombinationIterator {
    int m, n;
    int state;
    string s;
public:
    CombinationIterator(string characters, int combinationLength) {
        m = characters.length();
        n = combinationLength;
        s = characters;
        state = 0;
        for(int i = m; i > m - n; --i) {
            state += (1 << (i-1));
        }
    }
    
    string next() {
        string ret = "";
        
        for(int i = m - 1; i >= 0; --i) {
            if((state>>i)&1) ret.push_back(s[m-i-1]);
        }
        cout << state << endl;
        
        do{
            state--;
        } while(__builtin_popcount(state) != n && state > 0);
        
        
        return ret;
    }
    
    bool hasNext() {
        return state;
    }
};

/**
 * 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();
 */

Leave a Reply

Your email address will not be published. Required fields are marked *