如下面代码:
import java.util.ArrayList;
public class FullSort
{
public static void main(String[] args)
{
String str = "2468";
FullSort fs = new FullSort();
ArrayList<String> list = fs.permutation(str);
System.out.println("Total num : " + list.size());
for(String s : list)
System.out.println(s);
System.out.println();
int[] arr = {1, 2, 3, 4};
fs.perm(arr, 0, arr.length-1);
}
public ArrayList<String> permutation(String str)
{
ArrayList<String> list = new ArrayList<String>();
if(str.length() == 1)
{
list.add(str);
}
else
{
String temp = "";
String left = "";
for(int i=0; i<str.length(); i++)
{
temp = str.charAt(i) + "";
left = str.substring(0, i) + str.substring(i+1);
for(String element : permutation(left))
{
list.add(temp + element);
}
}
}
return list;
}
public void perm(int[] arr, int k, int m)
{
if(k == m)
{
for(int i=0; i<=m; i++)
{
System.out.print(arr[i]);
}
System.out.println();
}
else
{
for(int i=k; i<=m; i++)
{
Swap(arr, k, i);
perm(arr, k+1, m);
Swap(arr, k, i);
}
}
}
public void Swap(int[] arr, int i, int j)
{
int temp = -1;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
输出结果就不显示了。
如下面代码:
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class FullSort2
{
public static void main(String[] args)
{
int[] arr = {1, 3, 5, 7};
StringBuffer sb = new StringBuffer();
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i=0; i<arr.length; i++)
{
sb.append(arr[i]);
list.add(arr[i]);
}
FullSort2 test = new FullSort2();
test.printAll(sb, "", list.size());
System.out.println();
test.printAll(list, "", list.size());
}
public void printAll(StringBuffer candidate, String prefix, int length)
{
if(prefix.length() == length)
{
System.out.println(prefix);
}
for(int i=0; i<candidate.length(); i++)
{
StringBuffer temp = new StringBuffer(candidate.toString());
String str = prefix+temp.charAt(i);
temp.deleteCharAt(i);
printAll(temp, str, length);
}
}
public void printAll(List<Integer> candidate, String prefix, int length)
{
if(prefix.length() == length)
{
System.out.println(prefix);
}
for(int i=0; i<candidate.size(); i++)
{
List<Integer> temp = new LinkedList<Integer>(candidate);
String str = prefix+temp.remove(i);
printAll(temp, str, length);
}
}
}
结果也不输出了。