Iterator for Combination LeetCode solution in C++

1
class CombinationIterator {
2
public:
3
vector<string> ans;
4
int j = 0;
5
void comb(int i, string &s, int k, string &t) {
6
if (i == s.size()) {
7
if (t.size() == k) ans.push_back(t);
8
return;
9
}
10
// Pick
11
t.push_back(s[i]);
12
comb(i + 1, s, k, t);
13
t.pop_back();
14
// NotPick
15
comb(i + 1, s, k, t);
16
}
17

18
CombinationIterator(string characters, int combinationLength) {
19
sort(characters.begin(), characters.end());
20
string t = "";
21
comb(0, characters, combinationLength, t);
22
}
23

24
string next() {
25
return ans[j++];
26
}
27

28
bool hasNext() {
29
if (j == ans.size()) return false;
30
return true;
31
}
32
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0