zoukankan      html  css  js  c++  java
  • 数学基础:一、排列算法(递归)

    排列采用递归的方式进行,算法如下:

    public class Lesson7_2 {
        /**
         * @param rest-目前未排列的数据,has-保存已经排列的数据及其顺序
         * @return void
         * @Description: 使用函数的递归(嵌套)调用,找出所有可能的排列顺序
         */
        public static void permutate(List<String> has, List<String> rest, List<List<String>> result) {
            // 未(待)排列的数据为空,说明已排列完,直接在result中保存结果
            if (rest.size() == 0) {
                result.add(has);
            } else {
                for (int i = 0; i < rest.size(); i++) {
                    // 为了不破坏递归前的原数据,设置临时变量tmpHas和tmpRest来保存中间值
                    List<String> tmpHas = new ArrayList<>(has);
                    tmpHas.add(rest.get(i));
                    // 将已准备排序的数据从未排序列表中移出
                    List<String> tmpRest = new ArrayList<>(rest);
                    tmpRest.remove(i);
                    // 递归调用,对于剩余的数据时行排列
                    permutate(tmpHas, tmpRest, result);
                }
            }
        }
    
        public static void main(String[] args) {
            ArrayList<String> restList = new ArrayList<String>(Arrays.asList("1", "2", "3"));
            List<List<String>> resultList = new ArrayList<>();
            Lesson7_2.permutate(new ArrayList<String>(), restList, resultList);
            System.out.println(resultList);
        }
    
    }
    
  • 相关阅读:
    指针与数组
    深入函数
    到底是使用指针还是引用 ,混合使用以及易错点
    返回值作为标志
    c++的引用(二)
    内联函数
    c++的引用
    指针总结以及常量指针与指向常量的指针与指向常量的常指针
    c++中的 堆和栈
    Java Messages Synchronous and Asynchronous
  • 原文地址:https://www.cnblogs.com/dulinan/p/12033000.html
Copyright © 2011-2022 走看看