fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. void swap(char *x, char *y)
  4. {
  5. char temp;
  6. temp = *x;
  7. *x = *y;
  8. *y = temp;
  9. }
  10. void permute(char *a, int l, int r)
  11. {
  12. static int count=0;
  13. count++;
  14. cout<<"Function permute() is called "<<count<<" time"<<endl;
  15. int i;
  16. if (l == r){
  17. for(int k=0;k<=r;k++)
  18. cout<<a[k];
  19. cout<<endl;
  20. }
  21. else
  22. {
  23. for (i = l; i <= r; i++)
  24. {
  25. cout<<"Before 1st swap i:"<<i<<" l:"<<l<<endl;
  26. swap((a+l), (a+i));
  27. cout<<"Permute() is being called - "<<endl;
  28. permute(a, l+1, r);
  29. cout<<"Before 2nd swap i:"<<i<<" l:"<<l<<endl;
  30. swap((a+l), (a+i)); //backtrack
  31. }
  32. }
  33. }
  34.  
  35. /* Driver program to test above functions */
  36. int main()
  37. {
  38. char str[] = "ABC";
  39. int n = strlen(str);
  40. permute(str, 0, n-1);
  41. return 0;
  42. }
  43.  
Success #stdin #stdout 0s 3144KB
stdin
Standard input is empty
stdout
Function permute() is called   1  time
Before 1st swap i:0   l:0
Permute() is being called - 
Function permute() is called   2  time
Before 1st swap i:1   l:1
Permute() is being called - 
Function permute() is called   3  time
ABC
Before 2nd swap i:1   l:1
Before 1st swap i:2   l:1
Permute() is being called - 
Function permute() is called   4  time
ACB
Before 2nd swap i:2   l:1
Before 2nd swap i:0   l:0
Before 1st swap i:1   l:0
Permute() is being called - 
Function permute() is called   5  time
Before 1st swap i:1   l:1
Permute() is being called - 
Function permute() is called   6  time
BAC
Before 2nd swap i:1   l:1
Before 1st swap i:2   l:1
Permute() is being called - 
Function permute() is called   7  time
BCA
Before 2nd swap i:2   l:1
Before 2nd swap i:1   l:0
Before 1st swap i:2   l:0
Permute() is being called - 
Function permute() is called   8  time
Before 1st swap i:1   l:1
Permute() is being called - 
Function permute() is called   9  time
CBA
Before 2nd swap i:1   l:1
Before 1st swap i:2   l:1
Permute() is being called - 
Function permute() is called   10  time
CAB
Before 2nd swap i:2   l:1
Before 2nd swap i:2   l:0