forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIterator for Combination.js
52 lines (40 loc) · 1.27 KB
/
Iterator for Combination.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* @param {string} characters
* @param {number} combinationLength
*/
var CombinationIterator = function(characters, combinationLength) {
this.combinations = [];
const buildAllCombination = (curString, masterString) => {
if(curString.length == combinationLength ){
this.combinations.push(curString);
}
if(curString.length > combinationLength ) return ;
for(let g=0; g<masterString.length; g++){
buildAllCombination(curString + masterString[g], masterString.slice(g+1));
}
}
//lets sort it first
characters = characters.split('').sort( (a, b) => a-b );
buildAllCombination('', characters); // lets build the combinations;
this.counter = 0;
};
/**
* @return {string}
*/
CombinationIterator.prototype.next = function() {
let res = this.combinations[this.counter];
this.counter++;
return res;
};
/**
* @return {boolean}
*/
CombinationIterator.prototype.hasNext = function() {
return this.counter < this.combinations.length;
};
/**
* Your CombinationIterator object will be instantiated and called as such:
* var obj = new CombinationIterator(characters, combinationLength)
* var param_1 = obj.next()
* var param_2 = obj.hasNext()
*/