题目描述
题目链接: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)
时间了,代码如下:
1 | class CombinationIterator { |
- 时间复杂度: O(2^n)
- 空间复杂度: O(2^k) k 是要求字符串长度