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
    
    
    
     
  • 相关阅读:
    Linux学习路径 -- 1、文件目录操作命令
    第一次认识Postman
    接口测试的基础理论
    浅浅记录一哈HTTP接口
    Linux 的安装和使用
    QTP11 安装笔记:win10
    fiddler的下载安装与配置
    adb 下载安装
    maven 下载 安装 环境配置
    idea 2018.3.4安装破解
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13193250.html
Copyright © 2011-2022 走看看