fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. #include <algorithm>
  5. using namespace std;
  6.  
  7. // 用于存储所有可能的退出顺序
  8. vector<string> result;
  9. // 模拟栈结构
  10. vector<int> stack;
  11. // 标记应用是否已退出
  12. vector<bool> visited;
  13.  
  14. // 回溯函数,生成所有可能的退出顺序
  15. void backtrack(int n, string current) {
  16. // 如果所有应用都已退出,将当前顺序加入结果集
  17. if (current.size() == n) {
  18. result.push_back(current);
  19. return;
  20. }
  21.  
  22. // 如果栈不为空,弹出栈顶元素(模拟退出栈顶应用)
  23. if (!stack.empty()) {
  24. int top = stack.back();
  25. stack.pop_back();
  26. backtrack(n, current + to_string(top));
  27. // 回溯,恢复栈的状态
  28. stack.push_back(top);
  29. }
  30.  
  31. // 遍历所有未退出的应用
  32. for (int i = 1; i <= n; ++i) {
  33. if (!visited[i]) {
  34. visited[i] = true;
  35. stack.push_back(i);
  36. backtrack(n, current);
  37. // 回溯,恢复应用的状态和栈的状态
  38. stack.pop_back();
  39. visited[i] = false;
  40. }
  41. }
  42. }
  43.  
  44. void clacExitMode(int n) {
  45. visited.resize(n + 1, false);
  46. backtrack(n, "");
  47. // 按字典序排序结果
  48. sort(result.begin(), result.end());
  49. // 输出所有结果
  50. for (const string& s : result) {
  51. cout << s << " ";
  52. }
  53. cout << endl;
  54. }
  55.  
  56. int main() {
  57. int n = 3;
  58. clacExitMode(n);
  59. return 0;
  60. }
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
123 123 123 123 123 132 132 132 132 132 213 213 213 213 213 231 231 231 231 231 312 312 312 312 312 321 321 321 321 321