zoukankan      html  css  js  c++  java
  • 47. Permutations II

    一、题目

      1、审题

      2、分析:

        给出一个有重复数字的整形数组,求其全排序。

    二、解答

      1、思路:

        方法一、在上一题的递归基础上,加上过滤条件。

            例如:对于 112,

            ①、将1固定在第一位,求后边的12的排序;

            ②、此时应将第二个 1 固定在第一位,但是,与①重复,过滤掉;

            ③、将 2固定在第一位,求 11的排序。

    public List<List<Integer>> permute2(int[] nums) {
            
            Arrays.sort(nums);
            
            List<List<Integer>> resultList = new ArrayList<List<Integer>>();
            
            callAllPerm(resultList, nums, 0, nums.length - 1);
            
            return resultList;
        }
        
        private void callAllPerm(List<List<Integer>> resultList, int[] nums, int from,
                int to) {
            
            if(from == to) {    // add
                List<Integer> list = new ArrayList<Integer>();
                for (int i = 0; i < nums.length; i++) {
                    list.add(nums[i]);
                }
                resultList.add(list);
            }
            else {
                Set<Integer>  isAppeared = new HashSet<Integer>();  // 起过滤作用
                for (int i = from; i <= to; i++) {
                    if(isAppeared.add(nums[i])) {        // 未添加过
                        swap(nums, i, from);
                        callAllPerm(resultList, nums, from + 1, to);
                        swap(nums, i, from);
                    }
                }
            }
        }

      

      方法二、直接求数组的字典序列。同 上一题。

  • 相关阅读:
    oracle单行函数 之 转换函数
    oracle单行函数 之 时间函数
    oracle单行函数 之 数字函数
    oracle单行函数 之 字符函数
    oracle 之 如何链接别人电脑的oracle
    轻应用介绍
    Web 目录枚举与遍历漏洞解决
    接口测试工具(Postman)
    Tomcat 编码不一致导致乱码
    持久化配置管理 diamond 使用简介
  • 原文地址:https://www.cnblogs.com/skillking/p/9633705.html
Copyright © 2011-2022 走看看