zoukankan      html  css  js  c++  java
  • 字符串递归

    题目:输入一个字符串,打印出该字符串中字符的所有排列。例如输入字符串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
    ",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
    ",pStr[i]);   
             printf("%s
    ",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;
    
    }

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

  • 相关阅读:
    SQL 存储过程分页
    SqlServer中代理作业实现总结
    firfox兼容性插件
    C#停靠栏组件 DockPanel Suite
    Web.Config加密
    osql
    prototype.js的Ajax对IE8兼容问题解决方案
    获取系统的字体
    基于RBAC的权限管理系统的实现经典
    c/s(C#)下Ftp的多文件上传及其上传进度
  • 原文地址:https://www.cnblogs.com/bluewelkin/p/4104026.html
Copyright © 2011-2022 走看看