zoukankan      html  css  js  c++  java
  • lintcode16- Permutations II- medium

    Given a list of numbers with duplicate number in it. Find all unique permutations.

    Example

    For numbers [1,2,2] the unique permutations are:

    [
      [1,2,2],
      [2,1,2],
      [2,2,1]
    ]

    递归。和前面的差不多,但维护一个boolean[] isVisited数组以保证同一数字前后顺序唯一。当前面的2还没有使用的时候,就不应该让后面的2使用。

    切记同元素问题处理要先sort!因为如果判断前后相同那要先把它们聚拢在一起。

    public class Solution {
        /*
         * @param nums:  A list of integers
         * @return: A list of unique permutations
         */
        public List<List<Integer>> permuteUnique(int[] nums) {
            // write your code here
            List<List<Integer>> result = new ArrayList<List<Integer>>();
    
            if (nums == null){
                return null;
            }
    
            if (nums.length == 0){
                result.add(new ArrayList<Integer>());
                return result;
            }
    
            boolean[] isVisited = new boolean[nums.length];
            //切记要先sort!!!不然下面判断相邻的相同就不对了
            Arrays.sort(nums);
            helper(new ArrayList<Integer>(), isVisited, nums, result);
            return result;
    
        }
        
        private void helper(List<Integer> current, boolean[] isVisited, int[] nums, List<List<Integer>> result){
            if(current.size() == nums.length){
                result.add(new ArrayList<Integer>(current));
            }
            
            for(int i = 0; i < nums.length; ++i){
                if(isVisited[i] || (i > 0 && nums[i] == nums[i - 1] && !isVisited [i - 1])){
                    continue;
                }
                isVisited[i] = true;
                current.add(nums[i]);
                helper(current, isVisited, nums, result);
                current.remove(current.size() - 1);
                isVisited[i] = false;
            }
        }
    }
  • 相关阅读:
    MySQL索引底层的实现
    mysql索引深入优化
    explain详解与索引最佳实践
    (MYSQL)回表查询原理,利用联合索引实现索引覆盖
    为什么重复值高的字段不能建索引(比如性别字段等)
    Spring的事务
    为什么要用Redis?Redis为什么这么快?
    spring AOP
    钩子教程
    钩子教程
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7568360.html
Copyright © 2011-2022 走看看