public class Perm { public static void perm(Object[] a, int k, int m) { if (k == m) for (int i = 0; i < a.length; i++) System.out.print(a[i]);
System.out.println(); else { for (int i = k; i <= m; i++) {
swap(a, k, i);
perm(a, k + 1, m);
swap(a, k, i); } } }
public static void main(String[] args)
{
Integer[] a = new Integer[6];
for (int i = 0; i < a.length; i++)
a[i] = new Integer(i);
perm(a, 0, 5);
}
public static void swap(Object[] a, int i, int j)
{
Object temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
算法思想:
对n个元素的数组进行全排列,
如果n = 1则无需排列;
如果n >= 2,则对首个元素的取可能的所有值,后面n-1个元素进行全排列(递归)。
时间复杂度:
T(n) = n (T(n-1) + b) = Θ(n*n!)