zoukankan      html  css  js  c++  java
  • 数学基础:二、组合算法(递归)

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

    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);
        }
    }
    
  • 相关阅读:
    金刚经与心经之比较
    ECMWF 和 GFS 模型
    LSTM之父Jürgen Schmidhuber评图灵
    STM32相关知识点
    最全C++11/14/17/20/23 的新特性代码案例
    C++ 在线工具
    如何在 Proteus 中设计 PCB
    STM32电源框图解析
    【新特性速递】填一个坑
    【新特性速递】表格加载速度足足 3 倍提升,爱了爱了
  • 原文地址:https://www.cnblogs.com/dulinan/p/12032999.html
Copyright © 2011-2022 走看看