Java string Arrangement Algorithm
Question: How many combinations can a maximum of 16 of the five ABCDE balls be extracted repeatedly?
For example, there are five combinations of a B C D E which can be composed of one ball, A combination of 5 + 4 + 3 + 2 + 1 = 15 (repeated arrangement of BA and AB is considered as one)
AA AB AC AD AE
BB BC BD BE
CC CD CE
DD DE
EE
The combination of three balls is (5 + 4 + 3 + 2 + 1) + (4 + 3 + 2 + 1) + (3 + 2 + 1) + (2 + 1) + 1 = 35
AAA AAB AAC AAD AAE
ABB ABC ABD ABE
ACC ACD ACE
ADD ADE
AEE
BBB BBC BBD BBE
BCC BCD BCE
BDD BDE
BEE
CCC CCD CCE
CDD CDE
CEE
DDD DDE
DEE
EEE
Sample Code:
1 import java. util. Recursive; 2 3/** 4 * is mainly implemented by recursion. The main idea is to divide a string into two segments for processing. First, extract the first string and use the following characters to piece it together. 5 */6 public class Zuhe {7 private static String str = "ABCDE"; // String 8 private static int n = 3; // selected number 9 private static int count = 0; // number of combinations 10 11 public static void main (String [] args) {12 new Zuhe (); 13} 14 15 public Zuhe () {16 bytes input = new bytes (System. in); 17 System. out. println ("Enter the number to be selected (less than" + str. length () + "count)"); 18 n = Integer. parseInt (input. nextLine (); 19 find ("", 0); 20 System. out. println ("Total" + count + "Combination"); 21 22} 23/** 24 * The first parameter represents the first character, the second parameter indicates the starting position of the vertex 25 */26 public static void find (String s, int I) {27 // Save the previous String 28 String temp = s; 29 // determine whether the request meets the requirement 30 if (s. length () = n) {31 count ++; 32 33 System. out. print (s + ""); 34 if (count % 10 = 0) 35 System. out. println (); 36 return; 37} 38 // cycle from the search point, wind position 39 for (int k = I; k <str. length (); k ++) {40 s = temp; 41 s + = str. charAt (k); 42 find (s, k); 43} 44} 45}