全排列
递归方法
public class Main {
static void swap(int[] arr, int i, int j) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
static void full(int[] arr, int start) {
if (start == arr.length - 1) System.out.println(Arrays.toString(arr));
else {
for (int i = start; i < arr.length; i++) {
swap(arr, start, i);
full(arr, start + 1);
swap(arr, start, i);
}
}
}
public static void main(String[] args) throws Exception {
full(new int[]{1,2,3,4}, 0);
}
}
字典排序
public class Main {
static void dict(int[] arr) {
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
while (true) {
int i;
for (i = arr.length - 2; i >= 0; i--) {
if (arr[i] < arr[i + 1]) break;
}
if (i == -1) break;
int j;
for (j = arr.length - 1; j > 0; j--) {
if (arr[j] > arr[i]) break;
}
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
Arrays.sort(arr, i + 1, arr.length);
System.out.println(Arrays.toString(arr));
}
}
public static void main(String[] args) throws Exception {
dict(new int[]{1, 1, 2, 4});
}
}