【问题标题】:All possible combinations of a word一个单词的所有可能组合
【发布时间】:2015-07-26 22:53:55
【问题描述】:

我正在参加一次工作面试,他们要求我生成一个给定 字符串 的所有可能排列的列表。我的解决方案效率低下,采访我的那个人告诉我,我应该使用递归。 有人知道这个问题吗?

【问题讨论】:

    标签: c string recursion permutation


    【解决方案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);
    }
    

    注意,在这段代码中,用户应该在索引参数中给出 0 所以最好像这样调用这个函数:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-16
      • 1970-01-01
      • 1970-01-01
      • 2018-02-02
      • 2022-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多