fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. #include <algorithm>
  5. using namespace std;
  6.  
  7. vector<string> result;
  8. vector<int> stack;
  9. vector<bool> visited;
  10.  
  11. void backtrack(int n, string current) {
  12. if (current.size() == n) {
  13. // 检查结果是否已存在,避免重复添加
  14. if (find(result.begin(), result.end(), current) == result.end()) {
  15. result.push_back(current);
  16. }
  17. return;
  18. }
  19.  
  20. if (!stack.empty()) {
  21. int top = stack.back();
  22. stack.pop_back();
  23. backtrack(n, current + to_string(top));
  24. stack.push_back(top);
  25. }
  26.  
  27. for (int i = 1; i <= n; ++i) {
  28. if (!visited[i]) {
  29. visited[i] = true;
  30. stack.push_back(i);
  31. backtrack(n, current);
  32. stack.pop_back();
  33. visited[i] = false;
  34. }
  35. }
  36. }
  37.  
  38. void clacExitMode(int n) {
  39. visited.resize(n + 1, false);
  40. backtrack(n, "");
  41. sort(result.begin(), result.end());
  42. for (const string& s : result) {
  43. cout << s << " ";
  44. }
  45. cout << endl;
  46. }
  47.  
  48. int main() {
  49. int n = 3;
  50. clacExitMode(n);
  51. return 0;
  52. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
123 132 213 231 312 321