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);
        }
    }
    
  • 相关阅读:
    扫雷游戏

    set
    map
    认识了个外国友人!
    插入排序算法
    复习 C语言
    有关于我的一点想法
    linux下的内存分布
    C语言-将输入的字符输出并将多个空格按照一个空格的方式输出
  • 原文地址:https://www.cnblogs.com/dulinan/p/12032999.html
Copyright © 2011-2022 走看看