基础练习 FJ的字符串
问题描述
FJ在沙盘上写了这样一些字符串:
A1 = “A”
A2 = “ABA”
A3 = “ABACABA”
A4 = “ABACABADABACABA”
… …
你能找出其中的规律并写所有的数列AN吗?
输入格式
仅有一个数:N ≤ 26。
输出格式
请输出相应的字符串AN,以一个换行符结束。输出中不得含有多余的空格或换行、
回车符。
样例输入
3
样例输出
ABACABA
问题描述
FJ在沙盘上写了这样一些字符串:
A1 = “A”
A2 = “ABA”
A3 = “ABACABA”
A4 = “ABACABADABACABA”
… …
你能找出其中的规律并写所有的数列AN吗?
输入格式
仅有一个数:N ≤ 26。
输出格式
请输出相应的字符串AN,以一个换行符结束。输出中不得含有多余的空格或换行、
回车符。
样例输入
3
样例输出
ABACABA
解题思路:由题意可以很自然地想到采用递归的方式来做,但递归的方式总是让我感觉占用了太多的内存,所以转而采取开辟一个非常大的字符数组用来储存要输出的字符,利用空间来换取时间。具体的操作就是将新的字符加到数据当中,然后将之前以及存在的字符再复制一遍。
递归代码:
#include<stdio.h>
void printS(int n) {
if (n == 0) return;
printS(n - 1);
printf("%c", 'A' + n - 1);
printS(n - 1);
}
int main() {
freopen("output.txt", "w", stdout);
int N;
scanf("%d", &N);
printS(N);
printf("\n");
return 0;
}
非递归代码:
#include<stdio.h>
#define MAX 2<<26-1
char s[MAX] = {'0'};
int main() {
int N, now = 1, i, j;
scanf("%d", &N);
freopen("out.txt", "w", stdout);
s[0] = 'A';
for (i = 1; i < N; i++) {
s[now++] = 'A' + i;
for (j = now; j < now * 2 - 1; j++)
s[j] = s[j - now];
now = j;
}
int num = 2 << N - 1;
for (int i = 0; i < num; i++)
printf("%c", s[i]);
printf("\n");
return 0;
}