문제: https://leetcode.com/problems/iterator-for-combination/
Iterator for Combination - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
class CombinationIterator {
public:
int n;
int k;
vector<string> combinations;
void backtrack(string& characters, int pos, string s, int k){
int n = characters.size();
if(k == s.size()){
combinations.push_back(s);
return;
}
if(n == pos){
return;
}
backtrack(characters, pos + 1, s, k);
backtrack(characters, pos + 1, s + characters[pos], k);
return;
}
CombinationIterator(string characters, int combinationLength) {
this->n = characters.size();
this->k = combinationLength;
backtrack(characters, 0, "", this->k);
int v = 1;
}
string next() {
string ret = combinations.back();
combinations.pop_back();
return ret;
}
bool hasNext() {
return !combinations.empty();
}
};
/**
* 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();
*/
class CombinationIterator {
public:
int n;
int k;
vector<string> combinations;
CombinationIterator(string characters, int combinationLength) {
this->n = characters.size();
this->k = combinationLength;
for(int bitmask = 0; bitmask < 1 << n; bitmask++){
int cnt = bitCount(bitmask);
if(cnt == k){
string curr = "";
for(int j = 0; j < n; j++){
if((bitmask & (1 << n - j - 1)) != 0){
curr += characters[j];
}
}
combinations.push_back(curr);
}
}
}
int bitCount(int bitmask){
int ret = 0;
for(int i = 0; i < 15; i++){
ret += bitmask & 1;
bitmask = bitmask >> 1;
}
return ret;
}
string next() {
string ret = combinations.back();
combinations.pop_back();
return ret;
}
bool hasNext() {
return (!combinations.empty());
}
};
/**
* 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();
*/
'* Computer Science > Algorithm' 카테고리의 다른 글
739. Daily Temperatures (0) | 2021.11.13 |
---|---|
1178. Number of Valid Words for Each Puzzle (0) | 2021.11.10 |
1368. Minimum Cost to Make at Least One Valid Path in a Grid (0) | 2021.11.04 |
1202. Smallest String With Swaps (0) | 2021.11.03 |
1711. Count Good Meals (0) | 2021.10.28 |