Java如何实现全排列的三种算法详解

算法一 基于递归与回溯实现。在排列1,2,3的时候,先由3向上回溯到2发现没有其他可能的情况,再回溯到1,排列为1,3,2再向上回溯到存在其他情况时,即根节点然

算法一

基于递归与回溯实现。在排列1,2,3的时候,先由3向上回溯到2发现没有其他可能的情况,再回溯到1,排列为1,3,2再向上回溯到存在其他情况时,即根节点然后再排列以2为第一位的情况,重复上述过程将所有可能结果全部放入res中。

代码:

import java.util.ArrayList;
import java.util.List;
 
public class h618_1 {
 
    static List<List<Integer>> res = new ArrayList<>();
    public static void main(String[] args) {
        int[] arr = {1,2,3};
 
        h618_1 h1 = new h618_1();
        h1.dfs(arr,new ArrayList<>());
        for (List<Integer> re : res) {
            System.out.println(re);
        }
 
    }
 
    public List<List<Integer>> dfs( int[] arr,List<Integer> list){
        List<Integer> temp = new ArrayList<>(list);
        if (arr.length == list.size()){
            res.add(temp);
        }
        for (int i=0;i<arr.length;i++){
            if (temp.contains(arr[i])){
                continue;
            }
            temp.add(arr[i]);
            dfs(arr,temp);
            temp.remove(temp.size()-1);
        }
        return res;
    }
 
}

算法二

通过交换位置实现全排列:假设集合为{1,2,3,4};

循环交换位置:1和1交换;1和2交换;1和3交换;1和4交换;

每一次交换再通过递归调用更小的集合:

如:第一次1和1交换确定了1在第一位 所以可以看成 {1} + 递归交换{2,3,4};

第一次1和2交换确定了2在第一位 所以可以看成 {2} + 递归交换{1,3,4};

第一次1和3交换确定了3在第一位 所以可以看成 {3} + 递归交换{1,2,4};

第一次1和4交换确定了4在第一位 所以可以看成 {4} + 递归交换{1,2,3};

依次类推。

代码:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
public class h618_2 {
    static List<List<Integer>> res = new ArrayList<>();
    public static void main(String[] args) {
 
        int[] arr = {1,2,3};
        h618_2 h2 = new h618_2();
        h2.pailie_swap(0,arr);
 
    }
    public void pailie_swap(int index, int[] arr){
        if (arr.length==index){
            System.out.println(Arrays.toString(arr));
            return;
        }
        for (int i = index;i<arr.length;i++){
            swap(i,index,arr);
            pailie_swap(index+1,arr);
            swap(i,index,arr);
        }
 
    }
 
    public void swap(int i,int j ,int[] arr){
        int temp = arr[j];
        arr[j] = arr[i];
        arr[i] = temp;
 
    }
}

算法三

可以通过添加元素来实现全排列:

首先定义一个list 放入第一个元素为; 然后将剩余的元素依次插入之前的集合元素的所有可能的位置生成新的list;

例如:对{1,2,3,4}实现全排列

首先定义一个list 加入第一个元素为 {1}; 然后第二个元素2可以插入{1} 的前后两个位置形成新list :{21,12 },  第三个元素3分别插入list 的元素的所有位置 为:{321,231,213,312,132,123}; 以此类推。

代码:

import java.util.ArrayList;
 
public class h618_3 {
 
    public static void main(String[] args) {
        String aa = "123";
        h618_3 h3 = new h618_3();
        ArrayList<String> res = new ArrayList<>();
        res = h3.getP