数学基础:二、组合算法(递归)

组合算法也是使用递归算法产生组合结果

public class Lesson8_1 {
    /**
     * @Description 组合算法
     * @param has 已经选中要组合的数据
     * @param rest 剩余未(待)组合的数据
     * @param n 要选出的个数
     * @param resultList 组合结果
     */
    public static void combine(List<String> has, List<String> rest, int n, List<List<String>> resultList) {
        // 已达到选中的数量,直接添加到结果集中
        if (has.size() == n) {
            resultList.add(has);
        } else {
            int size = rest.size();
            for (int i = 0; i < size; i++) {
                // 为了不破坏递归前的原数据,设置临时变量tmpHas和tmpRest来保存中间值
                List<String> tmpHas = new ArrayList<>(has);
                // 从遍历的待组合数据中,取出一条数据作为组合的一个值
                tmpHas.add(rest.get(i));
                // 新的待组合结果只从选中后的数据中找,往前找只会和之前a, b或b, a这种重复
                List<String> tmpRest = new ArrayList<>(rest.subList(i + 1, size));
                // 递归调用,剩余待组合数据继续生成组合值
                combine(tmpHas, tmpRest, n, resultList);
            }
        }
    }

    public static void main(String[] args) {
        String[] arr = {"1", "2", "3", "4", "5"};
        List<String> restList = Arrays.asList(arr);
        List<List<String>> resultList = new ArrayList<>();
        combine(new ArrayList<>(), restList, 3, resultList);
        System.out.println(resultList);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值