Leecode 1286. Iterator for Combination
关键词:design, backtracking
思路:
- 建立ES6 class结构
- 在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;
};
};