数组全排列(递归)——Java

假设现在有6个数字进行全排列 (1,2,3,4,5,6)
那么就肯定有下列六种情况
=> 1,2,3,4,5,6
=> 2,1,3,4,5,6
=> 3,2,1,4,5,6
=> 4,2,3,1,5,6
=> 5,2,3,4,1,6
=> 6,2,3,4,5,1
再将选中部分进行全排列
也就是说,这组数据中出现的每一个数字都必须作为开头出现一次
根据这种原理,就可以写出一个递归算法来实现数组的全排列

public static void main(String[] args) {
    
    
	int A[] = new int[]{
    
    1, 2, 3};
    perm(A, 0);
}

public static void swap(int A[], int i, int j) {
    
    
    int temp = A[i];
    A[i] = A[j];
    A[j] = temp;
}

public static void printArray(int A[], int n) {
    
    
    for (int i : A) {
    
    
        System.out.print(i + " ");
    }
    System.out.println();
}

public static void perm(int A[], int p) {
    
    
    if (p == A.length) {
    
    
        printArray(A, A.length - 1);
    } else {
    
    
        for (int i = p; i < A.length; i++) {
    
    
            swap(A, i, p);
            perm(A, p + 1);
            swap(A, i, p);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/m0_46390568/article/details/107552223
今日推荐