Friday, 10 October 2014

Backtracking - permuation of a string

    //permuatiions using backtracking
    //programme to generate permutations of a string
//Algorithm Paradigm: Backtracking
//Time Complexity : O(n*n!)

#include<iostream>
#include<stdlib.h>
using namespace std;

void swap(char *x, char *y)
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;

}
// @params i is start index
// @params n is end index
void permute(char *a, int i, int n)
{
    int j;
    if (i == n)
        cout << "\n" << a;
    else
    {
        for (j = i; j <= n; ++j)
        {
            if( (a + i ) == ( a + j )  && i != j) continue;
            swap((a + i), (a + j));
            permute(a, i + 1, n);
            swap((a + i), (a + j)); //backtrack
        }
    }
}

/* Driver program to test above functions */
int main()
{
    char a[] = "ABC";
    permute(a, 0, 2);
    getchar();
    return 0;
}

No comments:

Post a Comment