xxxxxxxxxx
public static void permuteAndPrint(String str) {
permuteAndPrint("", str);
}
private static void permuteAndPrint(String prefix, String str) {
int n = str.length();
if (n == 0) {
System.out.print(prefix + " ");
} else {
for (int i = 0; i < n; i++) {
permuteAndPrint(prefix + str.charAt(i),
str.substring(i + 1, n) + str.substring(0, i));
}
}
}
xxxxxxxxxx
void permute(string a, int l, int r)
{
// Base case
if (l == r)
cout<<a<<endl;
else
{
// Permutations made
for (int i = l; i <= r; i++)
{
// Swapping done
swap(a[l], a[i]);
// Recursion called
permute(a, l+1, r);
//backtrack
swap(a[l], a[i]);
}
}
}
xxxxxxxxxx
# get all permutations of string
import itertools
for p in itertools.permutations('123'):
print(p) # ( ' 1 ', ' 2 ', ' 3 ') ( ' 1 ' , ' 3 ', ' 2 ' ) ( ' 2 ', ' 1 ', ' 3 ' )
xxxxxxxxxx
def permute(s):
if len(s) == 0:
return []
elif len(s) == 1:
return [s]
else:
permutations = []
for i in range(len(s)):
char = s[i]
remaining_chars = s[:i] + s[i+1:]
for p in permute(remaining_chars):
permutations.append(char + p)
return permutations
string = "abc" # Replace with the desired input string
print(permute(string))
xxxxxxxxxx
void permutation(string s)
{
sort(s.begin(),s.end());
do{
cout << s << " ";
}
while(next_permutation(s.begin(),s.end()); // std::next_permutation
cout << endl;
}