方法1:
public class PaiLie {// 对一组数字进行全排列
public static void main(String[] args) {
int a[] = new int[5];
for (int i = 1; i < a.length; i++)
a[i] = i;
pailie(a, 1);
}
public static void pailie(int[] a, int n) {// n 待交换数的索引
if (n < a.length - 1) {
for (int i = n; i < a.length; i++) {
int temp = a[i];
for (int k = i; k > n; k--)
a[k] = a[k - 1];
a[n] = temp; // 把该段最右面的数移到最左面
pailie(a, n + 1);
// 还原原来序列
for (int k = n; k < i; k++)
a[k] = a[k + 1];
a[i] = temp;
}
} else {
for (int j = 1; j < a.length; j++)
System.out.print(a[j] + " ");
System.out.println();
}
}
}
方法2:
public class PaiLie_2 {
public static void main(String[] args) {
final int N = 4;
int a[] = new int[N + 1];
for (int i = 1; i < a.length; i++)
a[i] = i;
pailie(a, 1, N);
} // 产生a[m:n]的所有排列
public static void pailie(int[] a, int m, int n) {
if (m == n) {
for (int j = 1; j <= n; j++)
System.out.print(a[j] + " ");
System.out.println();
} else
for (int i = m; i <= n; i++) {
swap(a, m, i);
pailie(a, m + 1, n);
swap(a, m, i);
}
}
// 交换数组中两个位置上的元素
public static void swap(int[] number, int i, int j) {
int t;
t = number[i];
number[i] = number[j];
number[j] = t;
}
}
温馨提示:答案为网友推荐,仅供参考