为了账号安全,请及时绑定邮箱和手机立即绑定

java递归问题,求助 很着急

java递归问题,求助 很着急

人到中年有点甜 2019-01-19 11:16:03
如有数组[["白色","黑色"],["64GB","128GB"],["中国移动","中国联通"]]要拼接返回一个数组如["白色/64GB/中国移动","黑色/64GB/中国移动","白色/128GB/中国移动","黑色/128GB/中国移动","白色/64GB/中国联通","黑色/64GB/中国联通","白色/128GB/中国联通","黑色/128GB/中国联通"] 有大神在吗?
查看完整描述

4 回答

?
Qyouu

TA贡献1786条经验 获得超11个赞

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

查看完整回答
反对 回复 2019-03-01
?
侃侃尔雅

TA贡献1801条经验 获得超16个赞

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));
    }
}

}
}

查看完整回答
反对 回复 2019-03-01
?
倚天杖

TA贡献1828条经验 获得超3个赞

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

查看完整回答
反对 回复 2019-03-01
?
MMMHUHU

TA贡献1834条经验 获得超8个赞

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/中国联通
查看完整回答
反对 回复 2019-03-01
  • 4 回答
  • 0 关注
  • 542 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号