java递归问题,求助 很着急

如有数组[["白色","黑色"],["64GB","128GB"],["中国移动","中国联通"]]
要拼接返回一个数组
如["白色/64GB/中国移动","黑色/64GB/中国移动","白色/128GB/中国移动","黑色/128GB/中国移动","白色/64GB/中国联通","黑色/64GB/中国联通","白色/128GB/中国联通","黑色/128GB/中国联通"]

有大神在吗?

阅读 2.7k
4 个回答

可用不用递归,三层循环可以解决你的问题
最外层循环遍历颜色,第二层循环遍历容量第三层循环遍历运营商

public class test {
public static List> source;

public static void main(String[] args) {

source = new ArrayList<>();

List<String> a = new ArrayList<String>();
a.add("黑色");
a.add("白色");
List<String> b = new ArrayList<String>();
b.add("64G");
b.add("128G");
List<String> c = new ArrayList<String>();
c.add("中国联通");
c.add("中国移动");
source.add(a);
source.add(b);
source.add(c);
ArrayList<String> result = new ArrayList<>();
recursion(result, source.get(0), 0, "");
System.out.println(result);

}

public static void recursion(List<String> result, List<String> para, int num, String choose) {

for (int i = 0; i < para.size(); i++) {
    if (source.size() == num + 1) {
        result.add(choose + "/" + para.get(i));
    } else {
        recursion(result, source.get(num + 1), num + 1, choose + "/" + para.get(i));
    }
}

}
}

这是一个多个数组组合问题。
1.用for循环。用一个变量标记数组的个数,用length属性读取每个数组的长度,所以用for循环肯定是可以的。
2.用dfs(深度优先搜索)算法。

List<String> colors = List.of("白色", "黑色");
List<String> sizes = List.of("64GB", "128GB");
List<String> ops = List.of("中国移动", "中国联通");

Stream.of(colors.toArray())
        .map(color ->
            Stream.of(sizes.toArray())
                    .map(size ->
                        Stream.of(ops.toArray())
                                .map(op -> String.format("%s/%s", size, op))
                                .collect(Collectors.toList()))
                    .flatMap(Collection::stream)
                    .map(concat -> String.format("%s/%s", color, concat))
                    .collect(Collectors.toList()))
        .flatMap(Collection::stream)
        .forEach(System.out::println);

输出:

白色/64GB/中国移动
白色/64GB/中国联通
白色/128GB/中国移动
白色/128GB/中国联通
黑色/64GB/中国移动
黑色/64GB/中国联通
黑色/128GB/中国移动
黑色/128GB/中国联通
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题