Today, in the work of a problem, enter in Java , such as three-a-line number I want to get all of its permutations, such as 123,312,132,231,213,321 of these
On the internet to find someone else's algorithm, a little finishing, share to everyone code as follows
Import Java.util.Arrays; Used for array output.
Import java.util.LinkedList;
Import java.util.List;
public class Test
{
static String tobearranged = "123456"; The string to be arranged.
Static string[] Array = Stringtostringarray (tobearranged); Convert it to an array. {"1", "2" ...}
static int length=array.length; The string length.
static int k=0; count when storing arrays.
Static string[] result=new string[total (length)]; The size of the array is the factorial of length.
public static void Main (string[] args)
{
Listall (arrays.aslist (array), "");
System.out.println (arrays.tostring (result)); Output.
}
The main calculation method.
public static void Listall (List candidate, String prefix)
{
if (Prefix.length () ==length)//less than the combination of string lengths is ignored.
{
Result[k++]=prefix; stored in the array.
}
for (int i=0;i
{
List tmp = new LinkedList (candidate);
{
Listall (tmp, prefix + tmp.remove (i)); The arguments in the function are parsed from the right
}
}
}
Converts a string to an array.
Static string[] Stringtostringarray (String s)
{
int Length=s.length ();
if (length<=0)
{
return new string[0];
}
String[] Result=new string[length];
for (int i=0;i
{
Result[i]= "" +s.charat (i);
}
return result;
}
Calculates the number factorial, which is the capacity of the resulting array.
static int total (int number)
"Any number of numbers in Java gets all of its permutations"