当前位置: 代码迷 >> 综合 >> Leetcode 1286. 字母组合迭代器(DAY 107) ---- 回溯算法学习期
  详细解决方案

Leetcode 1286. 字母组合迭代器(DAY 107) ---- 回溯算法学习期

热度:21   发布时间:2023-11-17 18:25:44.0

原题题目

在这里插入图片描述


代码实现(首刷自解)

class CombinationIterator {
    
public:void backtracking(const string& characters,vector<string>& ret,vector<bool>& visit,int pos,int combinationLength,string& temp){
    if(temp.size() == combinationLength){
    ret.emplace_back(temp);return;}    for(int i=pos;i<visit.size();++i){
    if(visit[i])  continue;visit[i] = true;string str = temp+characters[i];backtracking(characters,ret,visit,i+1,combinationLength,str);visit[i] = false;}return;}vector<string> ret;int pos;CombinationIterator(string characters, int combinationLength) {
    vector<bool> visit(characters.size(),false);string temp;backtracking(characters,ret,visit,0,combinationLength,temp);pos = 0;}string next() {
    return ret[pos++];}bool hasNext() {
    if(ret.size() == pos) 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();*/