JAVASCRIPT Leecode 1286. Iterator for Combination

Leecode 1286. Iterator for Combination

关键词:design, backtracking

思路

  1. 建立ES6 class结构
  2. 在constructor中,建立一个数组存放所有这个字符串的组合结构,时间复杂度是C(n k), 也就是O(n ^ min(k, n-k))。组合结构由backtrack回溯实现。

题目
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

解答

/**
 * @param {string} characters
 * @param {number} combinationLength
 */
class CombinationIterator  {
    constructor(characters, combinationLength){
        //create a array for display all combinations 
        this.res = []; //"abc" => ["ab", "bc", "ac"]
        this.index = 0;
        backTrack = (str, start) => {
            if (str.length == combinationLength){
                this.res.push(str);
                return;
            }
            for (let i = start; i < characters.length; i++){
                str += characters[i];
                backTrack(str, i+1);
                str = str.slice(0, -1); //same as cur.slice(0, str.length-1); remove last one. cur.slice(0,-2) : remove last two
            }
        }
        backTrack('', 0);
    }
    next() {
        const cur = this.res[this.index];
        this.index++;
        return cur;
    };
    hasNext() {
        if (this.res[this.index]) return true;
        return false;
    };
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值