全排列递归实现 Java
写递归函数的时候一定不要将递归一层一层的展开
需要先明确递归函数的功能
import java.util.Arrays;
import java.util.Scanner;
public class perm{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int arr[] = new int [n];
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
permutation(arr,0);//调用递归函数
}
public static void permutation(int []arr, int k) {
//终止条件
if (k == arr.length - 1) {
System.out.println(Arrays.toString(arr));
}else {
for (int i = k; i < arr.length; i++) {
swap(arr,k,i);
permutation(arr, k+1);//调用自身
swap(arr,k,i);
}
}
}
public static void swap(int []arr ,int k, int i) {
int t = arr[k];
arr[k] = arr[i];
arr[i] = t;
}
}