-
题目:已知某一个字母序列,把序列中的字母按出现顺序压入一个栈,在入栈的任意过程中,允许栈中的字母出栈,求所有可能的出栈顺序
-
题目链接:https://www.nowcoder.com/practice/37dafde80fa2445d91f6d7ae18795668
-
思路:我觉得是回溯问题,用DFS,然后设置一个字符串seq来保存出栈的字符,当符合条件输出字符串seq即可。
-
注意:入栈出栈一定要记得恢复状态。
解答: 8ms, 404k内存。
#include <iostream>
#include <string>
#include <stack>
using namespace std;
stack<char> s;
string str;
//seq即存放了要输出的字符串。(回溯得到的)
void traverse(stack<char> s, int count, string seq) {
if (count == str.size() && s.size()== 0) {
cout << seq << endl;
return;
}
//出栈
if (s.size() > 0) {
char topElement = s.top();
seq.push_back(topElement);
s.pop();
traverse(s, count, seq);
//恢复状态
s.push(topElement);
seq.pop_back();
}
//进栈
if (count < str.size()) {
s.push(str[count]);
traverse(s, ++count, seq);
//恢复状态
s.pop();
count--;
}
}
int main() {
cin >> str;
int count = 0;
traverse(s, count, "");
return 0;
}