一个单词的所有可能组合

时间:2015-05-15 05:43:57

标签: c string recursion permutation

我正在接受面试,他们让我生成一个列出了字符串的所有排列的列表。我的解决方案效率低下,采访我的人告诉我,我应该使用递归。 有谁知道这个问题?

1 个答案:

答案 0 :(得分:1)

这是一个经典的采访问题,解决方案就是这样:

int permu(char* str, size_t len ,size_t index )
{   
    size_t i = index - 1;

    if(index == len) { printf ("%s\n",str); } 

    while (++i < len)
    { 
        swap (str,index,i);           /* swap between index and i */
        permu(str, len ,index + 1 );  /* recorsion */
        swap (str,index,i);           /* swap back between index and i */
    }

    return(0);
}

请注意,在此代码中,用户应在索引parmether中给出0 所以最好这样调用这个函数:

int permutations(char* str, size_t len)
{
    return (permu(str, len ,0));
}

static int permu(char* str, size_t len ,size_t index )
{ //....}