字符串递归

题目:输入一个字符串,打印出该字符串中字符的所有排列。例如输入字符串abc,则输出由字符a、b、c所能排列出来的所有字符串abc、acb、bac、bca、cab和cba。

分析:这是一道很好的考查对递归理解的编程题,因此在过去一年中频繁出现在各大公司的面试、笔试题中

还是先来一张图片比较好说明:先固定好第一个数,然后后面的数再一次排列。如下图(0,3)代表【0,3)。(1,3)代表【1,3)

 

例一:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void f(char *str, int len, int n)
{   
    int i;   
    char tmp;   
    char *p = (char *)malloc(sizeof(*str));   
    if(n==len-1){                   //只剩一个元素
        printf("%s\n",str);         //打印
    }else{   
        for(i=n;i<len;i++){   
            strcpy(p,str);   

            tmp = *(str+n);         //交换两个字符
            *(str+n) = *(str+i);   
            *(str+i) = tmp;   

            f(str,len,n+1);   
            strcpy(str,p);            //恢复
        }   
    }   
    free(p);   
}   

int main(int argc, char **argv)
{   
    char str[] = "abcd";
    int len=strlen(str);   
    f(str,len,0);   
     
    return 0;   
}

 参考文章:http://blog.csdn.net/wuzhekai1985/article/details/6643127

http://blog.csdn.net/wzy_1988/article/details/8939140

实现二:

#include <stdio.h>
#include <string.h>
//函数功能 : 求一个字符串某个区间内字符的全排列  
//函数参数 : pStr为字符串,begin和end表示区间  
//返回值 :   无  
//九度1369 
void swap(char *a,char *b)
{
    char temp;
    temp=*a;
    *a=*b;
    *b==temp;    
}
void Permutation_Solution1(char *pStr, int begin, int end)  
{  
   char *p = (char *)malloc(sizeof(*pStr));   

    if(begin == end - 1) //只剩一个元素  
    {  int i;    
        //for(i = 0; i < end; i++) //打印     printf("%c\n",pStr[i]);   
         printf("%s\n",pStr);                  
    }  
     else  
    {  int k;
       char tmp;
        for(k = begin; k < end; k++)  
        {  
          strcpy(p,pStr); 
           tmp = *(pStr+begin);         //交换两个字符
            *(pStr+begin) = *(pStr+k);   
            *(pStr+k) = tmp;   


             Permutation_Solution1(pStr, begin + 1, end);  //递归 
               strcpy(pStr,p); 
        }  
    } 
   
}  

int main(void)
{
      char str[] = "abc";
      int len = strlen(str);
        Permutation_Solution1(str, 0, len);  
      return 0;

}

 

例一去掉重复的排列应该可以通过

posted @ 2014-11-17 17:33  kin2321  阅读(667)  评论(0编辑  收藏  举报