#include <cstdio>
#include <iostream>
#include <vector>
#include <stack>
using namespace std;

vector<string>result;//保存结果
string path;//保存每一种出栈序列
stack<char>st;

void backtracking(int index,string str){
    //终止条件->遍历完了
    if(index==str.size()){
        //1.遍历完了但是栈没空->把栈里的数据模拟出栈的样式一一读取出来,只是读取不是真的出栈,数据还在栈里保持原样方便回溯,path也应该保持原样方便回溯
        stack<char>temp;
        string temp_path=path;
        while(!st.empty()){
            char top=st.top();
            temp.push(top);
            path+=top;
            st.pop();
        }
        while(!temp.empty()){
            st.push(temp.top());
            temp.pop();
        }
        //2.遍历完了栈也空了,结果都在path里直接保存
        result.push_back(path);
        path=temp_path;
        return;
    }

    //单个节点的处理逻辑
    //1.可以入栈
    st.push(str[index]);
    backtracking(index+1,str);
    st.pop();
    //2.可以不入先把前边的出完再入
    if(!st.empty()){
        char top=st.top();
        st.pop();
        path+=top;
        backtracking(index,str);//因为这时候str[index]没有入栈所以不能index+1
        st.push(top);
        path.pop_back();
    }
}
int main() {
    string str;
    cin>>str;
    backtracking(0,str);
    for(auto e:result)
        cout<<e<<endl;
}

回溯是在模拟所有可能的入栈方式,出栈的结果要自己读取(不能影响回溯本来的入栈进度)

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐