二维arraylist的排列

我正在尝试制作一个二维数组列表,其中包含递归的每个可能的组合,例如1,2,3,4。 没有双倍的上升。

例如。
1,0,0
2,0,0
3,0,0
4,0,0
1,2,0
1,3,0
1,4,0
1,2,3
等等…

到目前为止我有

//this gives me all my numbers for(int i =0;i<arraySize;i++) index[i] = i; // and is the part that make the combinations for(int i = 0;i<arraySize;i++){ for(int x = 0;x<k;x++) combinations.get(i).set(x, index[i]); 

编辑:另外我不打算打印结果我想将结果存储在二维数组中

您正在寻找的是Backtracking 。 这种解决问题的技术很大程度上基于递归。 基本上,你设置你的第一个数字,然后只考虑其他数字作为子问题,并且当找到第一个数字集的每个排列时,第一个数字递增,等等。

您也可以使用直接的4 for循环来解决问题,但解决方案不会扩展到除4个数字之外的任何其他内容。

您的解决方案将如下所示。 它将输出4个数字的每个排列。

 public class PermutationDemo { public static void main(String[] args) { int[] array = new int[4]; for (int i=0; i 

结果是:

 PS [10:21] Desktop > java PermutationDemo 1 1 1 1 1 2 1 1 3 1 1 4 1 2 1 1 2 2 1 2 3 1 2 4 1 3 1 1 3 2 1 3 3 1 3 4 1 4 1 1 4 2 1 4 3 1 4 4 2 1 1 2 1 2 2 1 3 2 1 4 2 2 1 2 2 2 2 2 3 2 2 4 2 3 1 2 3 2 2 3 3 2 3 4 2 4 1 2 4 2 2 4 3 2 4 4 3 1 1 3 1 2 3 1 3 3 1 4 3 2 1 3 2 2 3 2 3 3 2 4 3 3 1 3 3 2 3 3 3 3 3 4 3 4 1 3 4 2 3 4 3 3 4 4 4 1 1 4 1 2 4 1 3 4 1 4 4 2 1 4 2 2 4 2 3 4 2 4 4 3 1 4 3 2 4 3 3 4 3 4 4 4 1 4 4 2 4 4 3 4 4 4 

另一种非递归选项。 我对“部分”排列使用“单词”,对数字使用“符号”:

 /** * Expands the set of existing words by adding non-repeated symbols to their right * @param symbols to choose from * @param existing words (may include the empty word) * @param expanded result */ public static void expand(ArrayList symbols, ArrayList> existing, ArrayList> expanded) { for (ArrayList prev : existing) { Integer last = prev.isEmpty() ? null : prev.get(prev.size()-1); for (Integer s : symbols) { if (last == null || s > last) { ArrayList toAdd = new ArrayList<>(prev); toAdd.add(s); expanded.add(toAdd); } } } } public static void main(String[] args) { ArrayList symbols = new ArrayList<>( Arrays.asList(new Integer[]{1, 2, 3, 4})); ArrayList> prev = new ArrayList<>(); ArrayList> next = new ArrayList<>(); ArrayList> aux; ArrayList> output = new ArrayList<>(); // add empty prev.add(new ArrayList()); // expand empty, then expand that expansion, and so on and so forth for (int i=0; i o : output) { for (int i : o) System.out.print(i); System.out.println(); } } 

并且输出与原始问题匹配(这似乎不是要求实际排列,至少根据提供的示例):

 1 2 3 4 12 13 14 23 24 34 123 124 134 234 1234 

作为关于java中集合操作的一般提示,我建议您查看Google Guava中的实用程序类,它可以帮助您完成大部分繁重工作,并确保您不会遇到性能问题。

然后,下一步是寻找适合您需求的方法。 例如, Collections2.permutations可能就是你要找的东西。

最后,如果你想自己实现这个算法练习,你可以查看guava或Groove Collection API的源代码来获取想法。