List all the combinations of numbers in an array, such as 1 and 2, listed as 12,21 ? Code
The idea is to fix the prefix prefix, and then there's the remaining candidate candidate. Select some of the candidates and add them back to the prefix.
For example, fix prefix 1, then add 2, then select 3 from the following 34, then 4. Get 1234. Or choose 4 from the back 34, then 3. Get 1243.
static void Listall (List candidate, String prefix) {
if (Candidate.isempty ()) {
System.out.println (prefix);
} for
(int i = 0; i < candidate.size (); i++) {
List temp = new LinkedList (candidate);
Listall (temp, prefix + temp.remove (i));
}
The code took advantage of some features, linkedlist delete operations faster, remove returned is the deleted elements
The function's arguments are parsed from the right, and after the remove, the value of the Temp pass is also a container with one less. In this way, the candidate gradually becomes smaller to reach the recursive jump condition. ? Use String to implement
static void Listall (string candidate, string prefix) {
if (candidate.length () = = 0) {
System.out.println (prefix) ;
}
for (int i = 0; i < candidate.length (); i++) {
char Prefixchar = Candidate.charat (i);
Listall (Candidate.replace (Prefixchar + "", ""), prefix + Prefixchar);
}
? Test
public static void Main (string[] args) throws IOException {
string[] arrays = new string[] {"1", "2", "3", "4"};
listall (Arrays.aslist (Arrays), "");
Listall ("1234", "");
}