companion1 2013-01-04 18:02
浏览 374
已采纳

C语言:给定3个字符,输入n,求长度为n的所有组合

C语言:给定3个字符,输入n,求长度为n的所有组合
如给定abc 输入 5,输出aaaaa,abcab 等等

  • 写回答

4条回答 默认 最新

  • 时光的IT小屋 2013-01-05 12:59
    关注

    [code="c"]

    #include "stdlib.h"
    #include "stdio.h"

    int strpos=0;

    void makeAry(char *buff,int bufflen, char *res,char *tmp,int tmplen,int pos){
    int i,j;
    for(i=0;i<bufflen;i++){
    tmp[pos]=buff[i];
    if(pos<tmplen-1){
    makeAry(buff,bufflen,res,tmp,tmplen,pos+1);
    }
    else{
    for(j=0;j<tmplen;j++){
    res[strpos*tmplen+j]=tmp[j];
    }
    strpos++;
    }
    }
    }

    int main(int argc, char* argv[])
    {
    int i,j;
    char buff[3];
    printf("Please input three letter:",buff);
    gets(buff);
    char buff2[10];
    printf("Please input a number:",buff2);
    gets(buff2);
    int len = atoi(buff2);
    long reslen = 3;
    for(i=0;i<len-1;i++){
    reslen*=3;
    }
    char res = (char)malloc(reslen*len);
    char tmp = (char)malloc(len);
    makeAry(buff,3,res,tmp,len,0);
    printf("It's %i groups:\n",reslen);
    for(i=0;i<reslen;i++){
    for(j=0;j<len;j++){
    printf("%c",res[len*i+j]);
    }
    printf("\n");
    }
    return 0;
    }
    [/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?