我有一个看起来像这样的设置:
List<int[]> list = new LinkedList<int[]>();
list.add(new int[] {1, 3, 4});
list.add(new int[] {4, 5});
list.add(new int[] {1, 4, 6});
我在编写代码时不知道数组的大小。我正在尝试遍历整个设置以生成所有可能的组合:
141
144
146
151
154
156
341
...
我目前正在使用递归来实现这一点:
public static void recursive(List<int[]> list) {
recursive(list, 0, "");
}
private static void recursive(List<int[]> list, int counter, String string) {
if (counter == list.size())
System.out.println(string);
else
for (int i: list.get(counter))
recursive(list, counter + 1, string + i);
}
我有两个问题:
我记得在一些讲座中听说递归总是可以用循环代替,但我不能在这种情况下这样做。这个循环版本看起来如何?
有没有更好的办法解决这个问题?
最佳答案
这里有一个非递归的方法来输出数组元素的所有组合。它肯定比递归解决方案更复杂。它的工作原理是在补充数组中记录最近在列表中的每个数组中输出的数字。
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class Iter {
public static void main(String[] args) {
List<int[]> list = new LinkedList<int[]>();
list.add(new int[] { 1, 3, 4 });
list.add(new int[] { 4, 5 });
list.add(new int[] { 1, 4, 6 });
iter(list);
}
private static void iter(List<int[]> list) {
int[] index = new int[list.size()];
Arrays.fill(index, 0);
boolean done = false;
do {
// Output digits for this row
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i)[index[i]]);
}
System.out.println();
// Rollover digits, starting from last
for (int j = list.size() - 1; j >= 0; j--) {
index[j] = (index[j] + 1) % list.get(j).length;
if (index[j] > 0) break;
if (j == 0) done = true;
}
} while (!done);
}
}
输出:
141
144
146
151
154
156
341
344
346
351
354
356
441
444
446
451
454
456
关于java - 遍历数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30291953/