这是一个使用方便的 varargs 参数的递归解决方案,因此适用于任意数量的数组:
public static String combinations(String s, char[]... arrays) {
if (arrays.length == 0) return s + "\n";
String result = "";
for (char c : arrays[0])
result += combinations(s + c, Arrays.copyOfRange(arrays, 1, arrays.length));
return result;
}
它不是那么有效,但它很简短。
您可以使用空白字符串直接调用它来启动它,但公共包装函数会产生更好的 API:
public static String combinations(char[]... arrays) {
return combinations("", arrays);
}
下面是一些测试代码:
char[] one = { 'a', 'b', 'c' };
char[] two = { '1', '2', '3' };
char[] three = { 'x', 'y', 'z' };
char[] four = { 'm', 'n', 'o' };
System.out.println(combinations(one, two, three, four));
输出:
a1xm
a1xn
a1xo
a1ym
a1yn
a1yo
a1zm
a1zn
a1zo
a2xm
a2xn
a2xo
a2ym
a2yn
a2yo
a2zm
a2zn
a2zo
a3xm
a3xn
a3xo
a3ym
a3yn
a3yo
a3zm
a3zn
a3zo
b1xm
b1xn
b1xo
b1ym
b1yn
b1yo
b1zm
b1zn
b1zo
b2xm
b2xn
b2xo
b2ym
b2yn
b2yo
b2zm
b2zn
b2zo
b3xm
b3xn
b3xo
b3ym
b3yn
b3yo
b3zm
b3zn
b3zo
c1xm
c1xn
c1xo
c1ym
c1yn
c1yo
c1zm
c1zn
c1zo
c2xm
c2xn
c2xo
c2ym
c2yn
c2yo
c2zm
c2zn
c2zo
c3xm
c3xn
c3xo
c3ym
c3yn
c3yo
c3zm
c3zn
c3zo