zoukankan      html  css  js  c++  java
  • C语言实例解析精粹学习笔记——30

    实例30:

           用已知字符串s中的字符,生成由其中n个字符组成的所有字符排列。设n小于字符串s的字符个数,其中s中的字符在每个排列中最多出现一次。例如,对于s[]="abc",n=2,则所有字符排列有:ba,ca,ab,cb,ac,bc。

    思路:

           实际上目前为止还是不能完全理解书中的程序,也不能在脑海中明确的构想出整个程序是如何递归的。对于这道题的大致思路理解如下:对于一个字符串abcdef的所有两个字母的排列用以下方式可能是比较清晰的,从字母a开始:

    1、ab,ac,ad,ae,af

    2、bc,bd,be,bf

    3、cd,ce,cf

    4、de,df

    5、ef

    在编写程序时,用一个全局字符数组存放要排列的字符,将a放在最后,依次遍历b,c,d,e,f。再将b放在倒数第二的位置,再进行遍历。直到所有内容完成。

           但是在具体编程时我是写不出来这种程序的,现把书中的解析及代码放到下面:

    #include <stdio.h>
    #include <stdlib.h>
    
    #define N 20
    
    char w[N];
    
    void perm(int n, char *s)
    {
        char s1[N];
        int i;
        int count = 0;
        if(n < 1)
            printf("%s\n",w);
        else
        {
            strcpy(s1, s);
            for(i=0; *(s1+i); i++)
            {
                *(w+n-1) = *(s1+i);
                *(s1+i)  = *s1;
                *s1      = *(w+n-1);
                count++;
                perm(n-1, s1+1);
            }
        }
    }
    
    int main()
    {
        int n = 2;
        char s[N];
        w[n] = '\0';
        printf("This is a char permutation program!\nPlease input a string:\n");
        gets(s);
        puts("Please input the char number of permuted:");
        scanf("%d", &n);
        puts("The permuted chars are:\n");
        perm(n,s);
        puts("\nPress any key to quit...");
        return 0;
    }
  • 相关阅读:
    iOS drewRect方法
    iOS中的单例
    iOS中类别的使用
    iOS存储的三种方式
    安卓上微信闪退的一种解决方法
    [Z] 通天塔导游:各种编程语言的优缺点
    怎样面对痛苦?
    [Z] 10 种必知必会的软件开发工具
    [Z] Linux 内核同步机制
    [Z] 囚禁你的精灵(daemon)进程
  • 原文地址:https://www.cnblogs.com/llccbb1/p/9703406.html
Copyright © 2011-2022 走看看