题目描述
题目链接:1286. Iterator for Combination
Design an Iterator class, which has:
- A constructor that takes a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments.
- A function next() that returns the next combination of length combinationLength in lexicographical order.
- A function hasNext() that returns True if and only if there exists a next combination.
例子
例子 1
CombinationIterator iterator = new CombinationIterator(“abc”, 2); // creates the iterator.
iterator.next(); // returns “ab” iterator.hasNext(); // returns true iterator.next(); // returns “ac” iterator.hasNext(); // returns true iterator.next(); // returns “bc” iterator.hasNext(); // returns false
Note
1 <= combinationLength <= characters.length <= 15
- There will be at most
10^4
function calls per test.- It’s guaranteed that all calls of the function
next
are valid.
解题思路
这道题我的思路就是先通过回溯的方式产生所有排列结果存在一个向量中,这个过程最长会用 O(2^n)
时间 但是存在剪枝所以实际不会用到这么长时间;对于 next()
和 hasNext()
都只需要 O(1)
时间了,代码如下:
class CombinationIterator {
public:
CombinationIterator(string characters, int combinationLength) {
m_characters = characters;
std::string current = "";
findCombination(0, combinationLength, current);
current_pos = 0;
}
string next() {
return combinations[current_pos++];
}
bool hasNext() {
return current_pos < combinations.size();
}
private:
std::string m_characters;
std::vector<std::string> combinations;
int current_pos;
void findCombination(int index, int combinationLength, std::string& current) {
if (current.length() == combinationLength) {
combinations.push_back(current);
return;
}
if (index == m_characters.length()) {
return;
}
for (int i = index; i < m_characters.length(); i++) {
current.push_back(m_characters[i]);
findCombination(i + 1, combinationLength, current);
current.pop_back();
}
}
};
- 时间复杂度: O(2^n)
- 空间复杂度: O(2^k) k 是要求字符串长度