本文共 1892 字,大约阅读时间需要 6 分钟。
请你设计一个迭代器类,包括以下内容:
示例:CombinationIterator iterator = new CombinationIterator("abc", 2); // 创建迭代器 iteratoriterator.next(); // 返回 "ab"iterator.hasNext(); // 返回 trueiterator.next(); // 返回 "ac"iterator.hasNext(); // 返回 trueiterator.next(); // 返回 "bc"iterator.hasNext(); // 返回 false 提示:1 <= combinationLength <= characters.length <= 15每组测试数据最多包含 10^4 次函数调用。题目保证每次调用函数 next 时都存在下一个字母组合。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/iterator-for-combination 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class CombinationIterator { vectorans; string path; int id = 0;public: CombinationIterator(string characters, int combinationLength){ dfs(characters, combinationLength, 0); } void dfs(string &s, int n, int idx) { if(path.size() == n) { ans.push_back(path); return; } for(int i = idx; i < s.size(); ++i) { path.push_back(s[i]); dfs(s, n, i+1);//下一个字符只能更大+1开始找 path.pop_back(); } } string next() { return ans[id++]; } bool hasNext() { return id < ans.size(); }};
32 ms 12.8 MB
class CombinationIterator { int bits; string s; int len;public: CombinationIterator(string characters, int combinationLength) { s = characters; bits = (1<0 && countOne(bits) != len) bits--; string t; for(int i = s.size()-1; i >= 0; --i) { if((bits>>i)&1) t += s[s.size()-i-1];//字符串是从左往右的,序号0开始 } bits--;//下一个数,下次搜索的起点 return t; } bool hasNext() { while(bits > 0 && countOne(bits) != len) bits--; return bits > 0; }};
20 ms 12 MB