问题描述
C语言:给定3个字符,输入n,求长度为n的所有组合如给定abc 输入 5,输出aaaaa,abcab 等等
解决方案
#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;}
解决方案二:
C31 * 5
解决方案三:
问下, 这三个字符是否可以有相同的?第二个问题:就是输入的n值是否可以比3小,这种情况怎么处理?
解决方案四:
用JAVA 写了个 不知道符不符合你的。因为手边没有C的开发环境。import java.util.ArrayList;import java.io.FileWriter;class Test {public static ArrayList<String> computer(String str,String makeStr,int max,int curTimes){ArrayList<String> lists = new ArrayList<String>();String newStr = makeStr;for(int j=0;j<str.length();j++){newStr += str.charAt(j);int t = curTimes+1;if(curTimes<max){lists.addAll(Test.computer(str,newStr,max,t));}else{lists.add(newStr);}newStr = makeStr;}return lists;}public static void main(String[] args)throws Exception{String str = "abc";int max = 5;ArrayList<String> lists = Test.computer(str,"",max,0); FileWriter f3 = new FileWriter ("file3.txt");StringBuffer sb = new StringBuffer();for(int i=0;i<lists.size();i++){sb.append(lists.get(i)+"rn");}f3.write(sb.toString());f3.close();}}