一个非常不好发现的错误:
先看代码:
#include <iostream>
using namespace std;
const int N = 22;
int ans[N], cnt;
int stk[N], tt, n;
int v[N], step = 1;
void dfs() {
if (cnt == n) {
for (int i = 0; i < n; ++i) {
cout << ans[i];
}
cout << '\n';
return;
}
if (tt) {
ans[cnt] = stk[tt]; // 出栈
cnt ++, tt --;
dfs();
cnt --, tt ++;
}
if (step <= n) {
stk[++tt] = step; // 入栈
step++;
dfs();
tt--;
step--;
}
}
int main() {
cin >> n;
dfs();
}
输入3, 输出为
123
133
233
233
333
问题在于22行的tt ++, 此时stk内部的值不是之前进入dfs内部的值, 而是后来修改后的3, 所以造成错误
所以自己手写栈一定要小心访问那些被弹出后的空间,这些空间可能不是之前时候的值了。故时间卡的不死能用STL就用STL。