-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathIterator for Combination.cpp
61 lines (42 loc) · 1.6 KB
/
Iterator for Combination.cpp
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
53
54
55
56
57
58
59
60
61
/*
Solution by Rahul Surana
***********************************************************
Design the CombinationIterator class:
CombinationIterator(string characters, int combinationLength) Initializes the object with a string
characters of sorted distinct lowercase English letters and a number combinationLength as arguments.
next() Returns the next combination of length combinationLength in lexicographical order.
hasNext() Returns true if and only if there exists a next combination.
***********************************************************
*/
#include <bits/stdc++.h>
class CombinationIterator {
public:
vector<string> x;
int j = 0;
void comb(int i, int n, string ch, int cl,string c){
if(i>n) return;
// cout << c <<" ";
if(c.length() == cl) { x.push_back(c); return; }
comb(i+1,n,ch,cl,c);
comb(i+1,n,ch,cl,c+ch[i]);
}
CombinationIterator(string characters, int combinationLength) {
comb(0,characters.length(),characters,combinationLength,"");
// for(auto m : x){cout << m <<" \n";}
sort(x.begin(),x.end());
}
string next() {
if(j >= x.size()) return "";
return x[j++];
}
bool hasNext() {
if(j == x.size()) return false;
return true;
}
};
/**
* Your CombinationIterator object will be instantiated and called as such:
* CombinationIterator* obj = new CombinationIterator(characters, combinationLength);
* string param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/