2014-02-08 26 views
-2

我给出了第一个数组的大小4。 (这将随测试案例而变化)。如何把permuations放到一个int数组中

让说的INT []的元素{1, 3, 3, 4}

什么算法或公式有使排列并把它们放到一个int [] []?

例如:在以上至3
a[0][] = {1, 3, 3}
a[1][] = {1, 3, 4}
a[2][] = {1, 3, 4}
a[3][] = {3, 3, 4}

组阵列的排列也记住,第一阵列的大小将不总是4,但它总是在3组中。

基本上我需要把一个int []的排列放到另一个r int [] []

+0

难以理解。 –

+0

对不起,基本上我需要把一个int []的排列放到另一个int [] []中。 – XT1shX

+0

看起来像https://stackoverflow.com/questions/20906214/permutation-algorithm-for-array-of-integers-in-java是相当接近你的问题的答案......(将“the”改为“一个“,因为毫无疑问有多个好的解决方案。) – keshlam

回答

0

最后我实现了permutation算法,用于任何大小的输入数组。这很有趣,这里是:

import java.util.Arrays; 

public class PermutationCalculator { 
    public static void main(String[] args) { 
     final int[] input = {1, 3, 3, 4}; 
     int[][] result = new PermutationCalculator().permutation(input); 

     // print result 
     for (int i = 0; i < input.length; i++) { 
      System.out.println(Arrays.toString(result[i])); 
     } 
    } 

    public int[][] permutation(int[] input) { 
     int[][] result = new int[input.length][]; // i-th row 
     for (int i = input.length - 1; i >= 0; i--) { 

      // negI starts from 0 instead of i which start from end 
      int negI = input.length - i - 1; 
      result[negI] = new int[input.length - 1]; 

      // j is row input array index, 
      // jj is column index (column length = input array -length - 1) 
      for (int j = 0, jj = 0; jj < input.length; j++, jj++) 
       if (jj == i) { 
        j--; // don't need increasing in this case 
       } else { 
        result[negI][j] = input[jj]; 
       } 
     } 

     return result; 
    } 
} 

输出是:

[1, 3, 3] 
[1, 3, 4] 
[1, 3, 4] 
[3, 3, 4] 
+0

谢谢这有助于很多! – XT1shX

相关问题