递归代替多重循环
我希望这个方法适用于任何给定数量的参数,我可以通过代码生成来做到这一点(有很多丑陋的代码),它可以通过递归来完成吗? 如果是这样怎么办? 我理解递归,但我不知道如何写这个。
private static void allCombinations(List<String>... lists) {
if (lists.length == 3) {
for (String s3 : lists[0]) {
for (String s1 : lists[1]) {
for (String s2 : lists[2]) {
System.out.println(s1 + "-" + s2 + "-" + s3);
}
}
}
}
if (lists.length == 2) {
for (String s3 : lists[0]) {
for (String s1 : lists[1]) {
System.out.println(s1 + "-" + s3);
}
}
}
}
I want this method to work for any given number of arguments, i can do that with code generation(with a lot of ugly code), can it be done with recursion? if so how? I understand recursion, but i dont know how to write this.
private static void allCombinations(List<String>... lists) {
if (lists.length == 3) {
for (String s3 : lists[0]) {
for (String s1 : lists[1]) {
for (String s2 : lists[2]) {
System.out.println(s1 + "-" + s2 + "-" + s3);
}
}
}
}
if (lists.length == 2) {
for (String s3 : lists[0]) {
for (String s1 : lists[1]) {
System.out.println(s1 + "-" + s3);
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一个简单的递归实现:
Here is a simple recursive implementation:
你特别需要它是递归的吗? 我会将其设为非递归,但仍然不是特殊情况:
Do you particularly need it to be recursive? I'd make it non-recursive but still not special case things:
这是一个通用的递归版本。 它抱怨测试代码中未经检查的通用数组创建,但排列代码本身没问题:
Here's a generalised recursive version. It complains about unchecked generic array creation in the test code, but the permute code itself is okay:
这是我基于 Rasmus 解决方案的具有正确排序的递归解决方案。 仅当所有列表的大小相同时它才有效。
允许不同大小的列表的“正确排序”解决方案必须从最后一个列表开始,并向后运行到第一个列表(lists[0]),将元素附加在“pre”字符串的开头或结尾并继续传递它。 同样,第一个列表将打印结果。 我本想编码的,但是午餐已经准备好了,女朋友开始不喜欢 stackoverflow 了……
here's my recursive solution with correct ordering, based on Rasmus' solution. it works only if all lists are of same size.
a "correct ordering" solution that allows lists of different sizes will have to start from the last list and work it's way backwards to the first list (lists[0]), appending the element at either beginning or end of the "pre" string and passing it onward. again, the first list will print the result. I'd have coded that, but lunch is ready and girlfriend is beginning to dislike stackoverflow...