This evening did the Huawei's machine test, 3 ACM problem, the last is to achieve from the M different characters in any combination of n characters.
Eg:input:ABC 2
Output:ab AC BC
The first input is a string, the second input is the number of characters combined, and "error" is output when n=0 or n>m.
Idea: You can use recursive algorithm to solve, for example, all combinations of 2 characters in ABC, first select a, that contains a 2 characters of all combinations is to take 1 characters from the remaining BC in all combinations, and then select the second B, All combinations of the 2 characters that contain B are the combination of 1 characters from the remaining C in the back, that is, only C, when the third C is selected, there are no characters behind, and it is not enough to compose a 2-character combination. And so on, all combinations of n characters from any of the M different characters are recursively recursive to all combinations of N-1 characters (containing "a") from M-1, plus all combinations of n characters (not "a") that are selected from each of the M-1 characters.
Import java.util.*;p Ublic class Main {public static void main (String args[]) { Scanner cin = new Scanner (system.in);
string str = Cin.next (); int maxCount = Cin.nextint (); char[] CHS = Str.tochararray (); if (maxcount==0 | | Maxcount>str.length ()) { System.out.print ("ERROR"); } Combination (CHS, 0, 0, MaxCount, ""); } / * * @param CHS input character Array * @param the array index value of the character selected by index * @param count has selected the number of characters * @param maxCount input to select Number of characters * @param result already selected character combination * * /public static void combination (char[] CHS, int index, int count, int MaxCount, String result) { if (count = = MaxCount) { System.out.print (result+ ""); return; } for (int i = index; i < chs.length; ++i) { combination (CHS, i + 1, Count + 1, maxCount, result + chs[i]); } }}
Huawei Machine Test ACM (character combination problem)