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);
                }
            }
        }
    }

  

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

原文地址:https://www.cnblogs.com/skillking/p/9633705.html