字母有重复排列(简单回溯)

转载请注明出处

题目描述

输出前N个字母的有重复全排列

Input

输入一个数值N 
1<=N<=10

Output

输出前N个大写字母的有重复全排列

Sample Input

2

Sample Output

AA
AB
BA
BB

第一种方法,回溯:
 1 #include <stdio.h>
 2 
 3 int n;
 4 char s[15];         
 5 char ss[15]={'A','B','C','D','E','F','G','H','I','J'};
 6 
 7 void dfs(int cur)           //cur表示第几个位置
 8 {
 9     if(cur==n)
10     {
11         printf("%s
",s);
12         return ;
13     }
14     for(int i=0;i<n;i++)        //每次从第一个字符A遍历,继续深搜
15     {
16         s[cur]=ss[i];           
17         dfs(cur+1);
18     }
19 }
20         
21 int main()
22 {
23     while(~scanf("%d",&n))
24     {
25         dfs(0);     
26     }
27     return 0;
28 }

第二种方法:模拟大数加法运算

 1 /**
 2     大数加法
 3     网址:http://www.codeup.cn/problem.php?id=2904
 4     题目:2904:字母有重复全排列[2*]
 5 */
 6 #include <iostream>
 7 #include <memory.h>
 8 #include <string.h>
 9 #include <stdio.h>
10 using namespace std;
11 void print(char str[],int N){
12     for(int i = 0; i < N; i++)
13         printf("%c",str[i]);
14     printf("
");
15 }
16 int main(){
17     int N;///输出前N个大写字母的有重复的全排列
18     char str[10],temp[10],flag[10];
19     char begin = 'A',end,*p=NULL;
20 // int f;
21 
22     while(scanf("%d",&N) != EOF){
23         end = begin + N - 1;
24         temp[0] = '';
25 
26         memset(flag,end,sizeof(flag));
27         memset(str,'A',sizeof(str));
28         flag[N] = str[N] = '';
29 
30         printf("%s
",str);
31         while(strcmp(str,flag) != 0){
32             p = str + N - 1;///指向最后一个字符
33 //            f = 0;
34             if(*p + 1 > end){
35                 while(*p + 1 > end){///AADD
36                     *p = 'A';
37                     --p;
38                     if(*p == end)
39                         continue;
40                     *p += 1;
41                     if(*p == end){
42                         print(str,N);
43                         break;
44                     }
45                     ///输出
46                     print(str,N);
47                 }
48             }else{///,AAAD
49                 *p += 1;
50                 ///输出
51                 print(str,N);
52             }
53         }
54     }
55     return 0;
56 }
原文地址:https://www.cnblogs.com/yfs123456/p/5402493.html