Permutation algorithm for array of integers in Java

前端 未结 9 2071
-上瘾入骨i
-上瘾入骨i 2020-11-29 12:56

I have a working example to generate all char permutations in a String as below:

static ArrayList permutations(String s) {
        if (s == nul         


        
9条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 13:05

    I've written that code some time ago, and edited a bit to match your requests. I hope it works.

    static ArrayList permutations(String s) {
        ArrayList ret = new ArrayList();
        permutation(s.toCharArray(), 0, ret);
        return ret;
    }
    
    public static void permutation(char[] arr, int pos, ArrayList list){
        if(arr.length - pos == 1)
            list.add(new String(arr));
        else
            for(int i = pos; i < arr.length; i++){
                swap(arr, pos, i);
                permutation(arr, pos+1, list);
                swap(arr, pos, i);
            }
    }
    
    public static void swap(char[] arr, int pos1, int pos2){
        char h = arr[pos1];
        arr[pos1] = arr[pos2];
        arr[pos2] = h;
    }
    

    UPDATE
    I just tried it on ideone.com. It seems to work. You're welcome. :)

    UPDATE 2
    It should basically be the same code with arrays of int's:

    static ArrayList permutations(int[] a) {
        ArrayList ret = new ArrayList();
        permutation(a, 0, ret);
        return ret;
    }
    
    public static void permutation(int[] arr, int pos, ArrayList list){
        if(arr.length - pos == 1)
            list.add(arr.clone());
        else
            for(int i = pos; i < arr.length; i++){
                swap(arr, pos, i);
                permutation(arr, pos+1, list);
                swap(arr, pos, i);
            }
    }
    
    public static void swap(int[] arr, int pos1, int pos2){
        int h = arr[pos1];
        arr[pos1] = arr[pos2];
        arr[pos2] = h;
    }
    

    UPDATE 3
    Works with int's too: http://ideone.com/jLpZow

提交回复
热议问题