Skip to content

Commit

Permalink
Merge pull request #83 from NishantTanwar/master
Browse files Browse the repository at this point in the history
Added Permutations of String problem in Backtrack Section
  • Loading branch information
srbcheema1 authored Oct 3, 2017
2 parents 7b4790a + fe627c1 commit 1f3ed6a
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions Backtrack/permutations_of_string.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Solution for printing all the permutations of a string.
#include<bits/stdc++.h>

/* Function to swap values at two pointers */
void swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}

/* Function to print permutations of string
This function takes three parameters:
1. String
2. Starting index of the string
3. Ending index of the string. */
void permute(char *a, int l, int r)
{
int i;
if (l == r)
cout<<a;
else
{
for (i = l; i <= r; i++)
{
swap((a+l), (a+i));
permute(a, l+1, r);
swap((a+l), (a+i)); //backtrack
}
}
}

int main()
{
char str[] = "ABC";
int n = strlen(str);
permute(str, 0, n-1);
return 0;
}
/*Output
ABC
ACB
BAC
BCA
CBA
CAB*/

0 comments on commit 1f3ed6a

Please sign in to comment.