使用java生成int数组的排列 - 错误

时间:2012-11-04 11:11:41

标签: java

我正在编写一个JAVA代码来生成整数数组的所有排列。 虽然我的排列数量正确,但排列本身并不正确。

在跑步时我获得:

Input array Length
3
1
2
3
0Permutation is
1,  2,  3,  
##########################
1Permutation is
1,  3,  2,  
##########################
2Permutation is
3,  1,  2,  
##########################
3Permutation is
3,  2,  1,  
##########################
4Permutation is
1,  2,  3,  
##########################
5Permutation is
1,  3,  2,  
##########################
6  number of permutations obtained
BUILD SUCCESSFUL (total time: 3 seconds)


public class PermulteArray {

    public static int counter = 0;

    public static void Permute(int[] input, int startindex) {
        int size = input.length;

        if (size == startindex + 1) {
            System.out.println(counter + "Permutation is");
            for (int i = 0; i < size; i++) {
                System.out.print(input[i] + ",  ");
            }
            System.out.println();
            System.out.println("##########################");
            counter++;
        } else {
            for (int i = startindex; i < size; i++) {

                int temp = input[i];
                input[i] = input[startindex];
                input[startindex] = temp;
                Permute(input, startindex + 1);
            }
        }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Input array Length");
        int arraylength = in.nextInt();
        int[] input = new int[arraylength];
        for (int i = 0; i < arraylength; i++) {
            input[i] = in.nextInt();
        }
        counter = 0;
        Permute(input, 0);
        System.out.println(counter + "  number of permutations obtained");
    }
}

9 个答案:

答案 0 :(得分:13)

int temp=input[i];
input[i]=input[startindex];
input[startindex]=temp;
Permute(input, startindex+1);

您在调用Permute之前已经交换了一个元素,但之后需要再次交换它,以便在for循环的迭代中保持元素的一致位置。

答案 1 :(得分:9)

这是迄今为止我见过的最佳解决方案:

public static void main(String[] args) {

int[] a={1,2,3,4,5,6};
permute(0, a);    
}

public  static void permute(int start, int[] input ) {
        if (start == input.length) {
            //System.out.println(input);
            for(int x: input){
            System.out.print(x);
        }
        System.out.println("");
        return;
    }
    for (int i = start; i < input.length; i++) {
        // swapping
        int temp = input[i];
        input[i] = input[start];
        input[start] = temp;
       // swap(input[i], input[start]);

        permute(start + 1, input);
       // swap(input[i],input[start]);

        int temp2 = input[i];
        input[i] = input[start];
        input[start] = temp2;
    }
}

答案 2 :(得分:1)

检查出来

for (int i = startindex; i < input2.length; i++) {
            char[] input = input2.clone();
            char temp = input[i];
            input[i] = input[startindex];
            input[startindex] = temp;
            permute(input, startindex + 1);
        }

答案 3 :(得分:1)

public class PermuteArray {

    public static void permute(char[] input2, int startindex) {

        if (input2.length == startindex) {
             displayArray(input2);
        } else {
            for (int i = startindex; i < input2.length; i++) {
                char[] input = input2.clone();
                char temp = input[i];
                input[i] = input[startindex];
                input[startindex] = temp;
                permute(input, startindex + 1);
            }
        }
    }


    private static void displayArray(char[] input) {
        for (int i = 0; i < input.length; i++) {
            System.out.print(input[i] + ";  ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        char[] input = { 'a', 'b', 'c', 'd'};
        permute(input, 0);
    }

}

答案 4 :(得分:1)

//This will give correct output 

import java.util.Scanner;

public class PermulteArray {

    public static int counter = 0;

    public static void Permute(int[] input, int startindex) {
        int size = input.length;

        if (size == startindex + 1) {
            System.out.println(counter + "Permutation is");
            for (int i = 0; i < size; i++) {
                System.out.print(input[i] + ",  ");
            }
            System.out.println();
            System.out.println("##########################");
            counter++;
        } else {
            for (int i = startindex; i < size; i++) {

                int temp = input[i];
                input[i] = input[startindex];
                input[startindex] = temp;
                Permute(input, startindex + 1);
                temp = input[i];
                input[i] = input[startindex];
                input[startindex] = temp;
            }
        }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Input array Length");
        int arraylength = in.nextInt();
        int[] input = new int[arraylength];
        for (int i = 0; i < arraylength; i++) {
            input[i] = in.nextInt();
        }
        counter = 0;
        Permute(input, 0);
        System.out.println(counter + "  number of permutations obtained");
    }

}

答案 5 :(得分:0)

您可以使用递归调用解决此问题。

https://github.com/Pratiyush/Master/blob/master/Algorithm%20Tutorial/src/arrays/Permutations.java

public void swap(int[] arr, int i, int j)
{
    int tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}

public void permute(int[] arr, int i)
{
    if (i == arr.length)
    {
        System.out.println(Arrays.toString(arr));
        return;
    }
    for (int j = i; j < arr.length; j++)
    {
        swap(arr, i, j); 
        permute(arr, i + 1);  // recurse call
        swap(arr, i, j);      // backtracking
    }
} 

public static void main(String[] args) {

    Permutations permutations = new Permutations();
    int[] arr = {1, 2, 3,4};
    permutations.permute(arr, 0);
}

此外,

还提供其他方法
  1. http://www.programcreek.com/2013/02/leetcode-permutations-java/
  2. http://www.programcreek.com/2013/02/leetcode-permutations-ii-java/

答案 6 :(得分:0)

以下要点是我使用过多次(主要用于测试目的)的解决方案。它基于众所周知的算法,以字典顺序生成排列(无递归):

   /**
     * Compute next (in lexicographic order) permutation and advance to it. 
     *
     * Find greater index i for which a j exists, such that: j > i and a[i] < a[j] (i.e. the 1st non-inversion).
     * For those j satisfying the above, we pick the greatest.
     * The next permutation is provided by swapping items at i,j and reversing the range a[i+1..n]
     */
    void advanceToNext()
    {
        // The array `current` is the permutation we start from

        // Find i when 1st non-inversion happens
        int i = n - 2;
        while (i >= 0 && current[i] >= current[i + 1])
            --i;

        if (i < 0) { 
            // No next permutation exists (current is fully reversed)
            current = null;
            return;
        }

        // Find greater j for given i for 1st non-inversion
        int j = n - 1;
        while (current[j] <= current[i])
            --j;

        // Note: The range a[i+1..n] (after swap) is reverse sorted 
        swap(current, i, j); // swap current[i] <-> current[j]
        reverse(current, i + 1, n); // reverse range [i+1..n]
    }

完整的解决方案(以类的形式)位于此处: https://gist.github.com/drmalex07/345339117fef6ca47ca97add4175011f

答案 7 :(得分:0)

对于这个问题,我有一个简单的答案,您可以尝试一下。

public class PermutationOfString {

 public static void main(String[] args) {
      permutation("123");
     }

     private static void permutation(String string) {
      printPermutation(string,"");
     }

     private static void printPermutation(String string, String permutation) {

      if(string.length()==0){
       System.out.println(permutation);
       return;
      }

      for (int i = 0; i < string.length(); i++) {
       char toAppendToPermutation = string.charAt(i);
       String remaining = string.substring(0, i) + string.substring(i + 1);

       printPermutation( remaining,  permutation + toAppendToPermutation);
      }  
     }       
} 

答案 8 :(得分:0)

import java.util.ArrayList;

公共类RecursivePermGen {

void permGen(int n, int m, ArrayList<Integer> cur) {
    if(m == 0) {
        System.out.println(cur);
        return;
    }
    for(int i = 1; i <= n; i++) {
        cur.add(0, i);
        permGen(n, m-1, cur);
        cur.remove(0);
    }

}

public static void main(String[] args) {
    RecursivePermGen pg = new RecursivePermGen();
    ArrayList<Integer> cur = new ArrayList<Integer>();

    pg.permGen(2, 2, cur);
}

}