fork download
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. std::vector<int> perm, chosen;
  6. int n = 3;
  7.  
  8. void print(const std::vector<int>& v)
  9. {
  10. for (int e : v) {
  11. std::cout << " " << e;
  12. }
  13. std::cout << std::endl;
  14. }
  15.  
  16. void search() {
  17. if (perm.size() == n) /// DEAD END
  18. {
  19. print(perm);
  20. }
  21. else {
  22. for (int i = 0; i < n; i++) {
  23.  
  24. if (chosen[i]) continue; /// you have already taken this in your current path , so ignore it now
  25.  
  26. chosen[i] = true; /// take it , as you haven't already
  27. perm.push_back(i);
  28.  
  29. search(); // go to the next step after taking this item
  30.  
  31. chosen[i] = false; // you have done all you could do with this , now get rid of it
  32. perm.pop_back();
  33. }
  34. }
  35. }
  36.  
  37. int main()
  38. {
  39. for(int i = 1; i <= n; i++) perm.push_back(i);
  40. search();
  41. }
Success #stdin #stdout 0.01s 5516KB
stdin
Standard input is empty
stdout
 1 2 3