LeetCode-1286. Iterator for Combination

Design an Iterator class, which has:

  • A constructor that takes a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments.
  • A function next() that returns the next combination of length combinationLength in lexicographical order.
  • A function hasNext() that returns True if and only if there exists a next combination.

 

Example:

CombinationIterator iterator = new CombinationIterator("abc", 2); // creates the iterator.

iterator.next(); // returns "ab"
iterator.hasNext(); // returns true
iterator.next(); // returns "ac"
iterator.hasNext(); // returns true
iterator.next(); // returns "bc"
iterator.hasNext(); // returns false

 

Constraints:

  • 1 <= combinationLength <= characters.length <= 15
  • There will be at most 10^4 function calls per test.
  • It's guaranteed that all calls of the function next are valid.

题解:

class CombinationIterator {
private:
    vector<string> dic;
    int idx = 0;
    void buildIterator(int begin, string &cur, int combinationLength, string &characters) {
        if (cur.length() == combinationLength) {
            dic.push_back(cur);
            return;
        }
        for (int i = begin + 1; i < characters.length(); i++) {
            cur += characters[i];
            buildIterator(i, cur, combinationLength, characters);
            cur.pop_back();
        }
    }
public:
    CombinationIterator(string characters, int combinationLength) {
        for (int i = 0; i < characters.size(); i++) {
            string cur;
            cur += characters[i];
            buildIterator(i, cur, combinationLength, characters);
        }
    }
    
    string next() {
        return dic[idx++];
    }
    
    bool hasNext() {
        return idx < dic.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();
 */

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值