我有一个看起来像这样的设置:
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});
Run Code Online (Sandbox Code Playgroud)
编写代码时我不知道数组的大小.我试图遍历整个设置以生成所有可能的组合:
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);
}
Run Code Online (Sandbox Code Playgroud)
我有两个问题:
我记得在一些讲座中听到递归总是可以用循环代替,但我不能为这种情况做.这个循环版本怎么样?
有没有更好的方法来解决这个问题?
我试图从自定义分布中生成随机数,我已经发现了这个问题: 从(任意)连续概率分布模拟, 但不幸的是它没有帮助我,因为方法建议需要分配函数的公式.我的分布是多个均匀分布的组合,基本上分布函数看起来像直方图.一个例子是:
f(x) = {
0 for x < 1
0.5 for 1 <= x < 2
0.25 for 2 <= x < 4
0 for 4 <= x
}
Run Code Online (Sandbox Code Playgroud)