forked from shivprime94/Data-Structure-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpermutations_backtracking.cpp
More file actions
52 lines (46 loc) · 924 Bytes
/
permutations_backtracking.cpp
File metadata and controls
52 lines (46 loc) · 924 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
void permute(string s, int i, vector<string> &ans){
if(i == s.length()){
ans.push_back(s);
return;
}
for(int j = i; j < s.length(); j++){
swap(s[i], s[j]);
permute(s, i + 1, ans);
// backtracking
swap(s[i], s[j]);
}
}
vector<string>find_permutation(string S)
{
vector<string> ans;
permute(S, 0, ans);
sort(ans.begin(), ans.end());
return ans;
}
};
// { Driver Code Starts.
int main(){
int t;
cin >> t;
while(t--)
{
string S;
cin >> S;
Solution ob;
vector<string> ans = ob.find_permutation(S);
for(auto i: ans)
{
cout<<i<<" ";
}
cout<<"\n";
}
return 0;
}
// } Driver Code Ends