java - 遍历数字数组的每个排列
问题描述
我的问题是这样的:我在一个数组中有 n 个数字,每个都有一个最大值 m,我想遍历这些数字的每个排列,通过单独递增它们直到它们达到最大值。
一个例子:
[0,0,0,0]
Integer @ index 0 has a max value of 5
Integer @ index 1 has a max value of 3
Integer @ index 2 has a max value of 4
Integer @ index 3 has a max value of 6
Output:
[0,0,0,1]
[0,0,0,2]
[0,0,0,3]
.
.
.
[0,1,1,0]
[0,1,1,1]
[0,1,1,2]
[0,1,1,3]
.
.
.
[5,0,2,1]
[5,0,2,2]
etc.
Python 有带有产品功能的 itertools,这可以解决我的问题,但它看起来不像 Java 有类似的东西。递归似乎是要走的路,但我可以找出前进的方向。
有谁知道如何实现上述输出?提前致谢 :-)
解决方案
从技术上讲,排列意味着某些元素的重新排序,例如,[3,1,2]
是 的排列[1,2,3]
。您所要求的等同于迭代笛卡尔积,因此 Python 函数被命名为product
.
正如您正确指出的那样,递归是这里的方法。这是因为生成所有序列[5,3,4,6]
需要生成所有序列,[3,4,6]
开头为 0,然后再次以 1 开头,依此类推,直到 5。
import java.util.Arrays;
public class CartesianProduct {
public static void main(String[] args) {
printAll(5, 3, 4, 6);
}
public static void printAll(int... maxes) {
int[] current = new int[maxes.length];
printAll(maxes, current, 0);
}
private static void printAll(int[] maxes, int[] current, int i) {
if(i == current.length) {
System.out.println(Arrays.toString(current));
} else {
int max = maxes[i];
for(int j = 0; j <= max; ++j) {
current[i] = j;
printAll(maxes, current, i+1);
}
}
}
}
变量i
是我们当前为其选择值的位置的索引,变量j
是该位置的当前值,数组current
保存当前序列。递归的基本情况是在所有地方都选择了值,所以我们打印。
推荐阅读
- python - 带有 python 请求的 Pushbullet API SSLerror
- javascript - IE 中的 CSS 文本框呈现问题
- python - 当我运行时,有些东西将我的 lambda 函数变成了 def 函数,我该如何解决这个问题?
- javascript - 链式承诺 - 返回的承诺解析不会导致调用 then 方法
- linux - /dev/bus/usb/xxx/yyy中代码背后的含义?
- javascript - JS - 如何在文本为空且未勾选复选框时停止表单提交?
- c# - 在 Visual Studio 中获取文件的内容而不从扩展中打开文件
- c - 对 char 使用按位运算
- docker - 带有 marklogic 图像的 docker commit 未按预期工作
- java - 生命周期配置未涵盖插件执行:org.codehaus.gmaven:groovy-maven-plugin:2.1.1