zoukankan      html  css  js  c++  java
  • 全排列2 · Permutations

    Given a collection of numbers that might contain duplicates, return all possible unique permutations.

    Example:

    Input: [1,1,2]
    Output:
    [
      [1,1,2],
      [1,2,1],
      [2,1,1]
    ]
    数组记得要排序
    一些问题不能理解,那就这样吧。本来中等的题目就不好理解,得考虑一下投入产出比了。

    public class Solution {
        /*
         * @param nums: A list of integers.
         * @return: A list of permutations.
         */
        public List<List<Integer>> permuteUnique(int[] nums) {
            //corner case
            List<List<Integer>> results = new ArrayList<>();
            List<Integer> permutations = new ArrayList<>();
            int[] visited = new int[nums.length];
            
            if (nums == null) {
                return null;
            }
            
            if (nums.length == 0) {
                //return new ArrayList<>();
                results.add(new ArrayList<>());
                return results;
            }
            
            
            Arrays.sort(nums);
            for (int i = 0; i < nums.length; i++) {
                visited[i] = 0;
            }
            
            //helper
            helper(nums, permutations, visited, results);
            //return
            return results;
        }
        //helper
        public void helper (int[] nums, List<Integer> permutations, 
        int[] visited, List<List<Integer>> results) {
            if (permutations.size() == nums.length) {
                results.add(new ArrayList<>(permutations));
                return ;//
            }
            
            for (int i = 0; i < nums.length; i++) {
                if (visited[i] == 1) 
                    continue;
                
                if ((i != 0) && (nums[i] == nums[i - 1]) && (visited[i - 1] == 0)) 
                    continue;
                
                permutations.add(nums[i]);
                visited[i] = 1;
                helper(nums, permutations, visited, results);
                visited[i] = 0;
                permutations.remove(permutations.size() - 1);
            }
        }
    }
    View Code
    
    
    
     
  • 相关阅读:
    C++11模板类使用心得
    Linux下MakeFile初探
    Leetcode 35 Search Insert Position 二分查找(二分下标)
    Leetcode 4 Median of Two Sorted Arrays 二分查找(二分答案+二分下标)
    数据库分库分表的应用场景及方法分析
    DB主从一致性的几种解决方法
    Redis主从复制和集群配置
    RPC vs RESTful
    Mysql锁详解
    BIO与NIO、AIO的区别
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13193250.html
Copyright © 2011-2022 走看看