Problem Description
FJ in the sand table to write some string like this:
A1 = "A"
A2 = "ABA"
A3 = "ABACABA"
A4 = "ABACABADABACABA"
... ...
you can find out the rules and write them all columns AN it?
Input Format
Only a few: N ≤ 26.
Output Format
Please output corresponding string AN, to a newline character. Output must not contain extra space or line feed, carriage return.
Sample input
3
Sample Output
Spearheading
Thinking
The examples given topic may be found Law:
A1 = "A"
An = An-new letter. 1 + + An-1
a new letter (char) 'A' n + - 1
can be seen a recursive solution to this problem
here given two kinds of recursive and recursive disassembly method
Code
import java.util.Scanner;
public class FJString {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
System.out.println(solution2(n));
System.out.println(solution1(n));
}
public static String solution1(int n) { //递归法
if(n == 1)
return "A";
String insert = String.valueOf((char) ('A' + n - 1));
return solution1(n - 1) + insert + solution1(n - 1);
}
public static String solution2(int n) { //递推法
String str = new String();
for (int i = 1; i <= n; i++) {
String insert = String.valueOf((char) ('A' + i - 1));
String str_new = str + insert + str;
str = str_new;
}
return str;
}
}