Web Toolbar by Wibiya

Pages

Thursday, January 19, 2012

Print all permutations of a given string.

Solutiom #1:

void permute(char* str, int len, int level)
{
    //if last character is reached, print the string
    if(len == 1)
    {
        printf("%s\n", str-level);
        return;
    }

    int i;

    for(i=0; i < len; i++)
    {
        //swap first charater with the ith character
        swap(&(str[0]), &(str[i]));

        //recursively permute rest of the string
        permute(str+1, len-1, level+1);
        
        //bring first character back to its position
        swap(&(str[0]), &(str[i]));
    }
}

int main()
{
    char str[20] = {0,};

    sprintf(str, "abcd");

    permute(str, strlen(str), 0);

    return 0;
}

No comments: