Java实现集合的组合(从组合中取出K个元素进行组合的所有情况)

本文介绍了一种使用递归方法实现的组合算法,该算法能够找出从指定列表中抽取特定数量元素的所有可能组合。通过示例展示了如何针对大小为3的列表找到所有大小为2的子集,并提供了测试代码及预期输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.利用递归进行取出数据:

 public static <T> List<List<T>> combinations(List<T> list, int k) {
        if (k == 0 || list.isEmpty()) {//去除K大于list.size的情况。即取出长度不足K时清除此list
            return Collections.emptyList();
        }
        if (k == 1) {//递归调用最后分成的都是1个1个的,从这里面取出元素
            return list.stream().map(e -> Stream.of(e).collect(toList())).collect(toList());
        }
        Map<Boolean, List<T>> headAndTail = split(list, 1);
        List<T> head = headAndTail.get(true);
        List<T> tail = headAndTail.get(false);
        List<List<T>> c1 = combinations(tail, (k - 1)).stream().map(e -> {
            List<T> l = new ArrayList<>();
            l.addAll(head);
            l.addAll(e);
            return l;
        }).collect(Collectors.toList());
        List<List<T>> c2 = combinations(tail, k);
        c1.addAll(c2);
        return c1;
    }

/**
*根据n将集合分成两组
**/
public static <T> Map<Boolean, List<T>> split(List<T> list, int n) {
        return IntStream
                .range(0, list.size())
                .mapToObj(i -> new SimpleEntry<>(i, list.get(i)))
                .collect(partitioningBy(entry -> entry.getKey() < n, mapping(SimpleEntry::getValue, toList())));
    }

2.测试用例如下:

 @Test
    public void shouldFindAllCombinationsOfSize2FromAListWithSize3() throws Exception {
        List<String> input = Stream.of("a", "b", "c").collect(toList());
        List<List<String>> combinations = P26.combinations(input, 2);
        System.out.println("2-->"+combinations.toString());
        assertThat(combinations, hasSize(3));
    }

3.测试结果如下:

2-->[[a, b], [a, c], [b, c]]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值