Skip to content

Commit 88b94e6

Browse files
authored
Update 1286-iterator-for-combination.js
1 parent 96bf44b commit 88b94e6

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

1286-iterator-for-combination.js

+51
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,54 @@ function build(max, str, out = [], curr = '') {
4141

4242
return out
4343
}
44+
45+
// another
46+
47+
/**
48+
* @param {string} characters
49+
* @param {number} combinationLength
50+
*/
51+
const CombinationIterator = function(characters, combinationLength) {
52+
const res = [], len = combinationLength, str = characters, n = str.length
53+
helper([], 0)
54+
this.arr = res
55+
this.idx = 0
56+
57+
function helper(cur, idx) {
58+
if(cur.length === len) {
59+
res.push(cur.slice().join(''))
60+
return
61+
}
62+
if(idx >= n) return
63+
64+
cur.push(str[idx])
65+
helper(cur, idx + 1)
66+
cur.pop()
67+
68+
helper(cur, idx + 1)
69+
}
70+
};
71+
72+
/**
73+
* @return {string}
74+
*/
75+
CombinationIterator.prototype.next = function() {
76+
if(this.hasNext()) {
77+
return this.arr[this.idx++]
78+
}
79+
};
80+
81+
/**
82+
* @return {boolean}
83+
*/
84+
CombinationIterator.prototype.hasNext = function() {
85+
return this.arr[this.idx] != null
86+
};
87+
88+
/**
89+
* Your CombinationIterator object will be instantiated and called as such:
90+
* var obj = new CombinationIterator(characters, combinationLength)
91+
* var param_1 = obj.next()
92+
* var param_2 = obj.hasNext()
93+
*/
94+

0 commit comments

Comments
 (0)