zoukankan      html  css  js  c++  java
  • [leetcode]47. 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]
    ]

    题意:

    打印全排列,注明了给定序列可含有重复元素

    Solution1: Backtracking

    code

     1 class Solution {
     2      public List<List<Integer>> permuteUnique(int[] nums) {
     3         List<List<Integer>> list = new ArrayList<>();
     4          List<Integer> path = new ArrayList<>();
     5         Arrays.sort(nums); // necessary!因为后面要查重
     6         dfs(list, path, nums, new boolean[nums.length]);
     7         return list;
     8 }
     9 
    10     private void dfs(List<List<Integer>> list, List<Integer> path, int [] nums, boolean [] used){
    11         if(path.size() == nums.length){
    12             list.add(new ArrayList<>(path));
    13             return;
    14         }
    15         for(int i = 0; i < nums.length; i++){
    16             if(used[i] || i > 0 && nums[i] == nums[i-1] && !used[i - 1]) continue;
    17             used[i] = true; //标记用过
    18             path.add(nums[i]);
    19             dfs(list, path, nums, used);
    20             used[i] = false; //恢复default值
    21             path.remove(path.size() - 1);
    22         }
    23     }
    24 }
  • 相关阅读:
    php system()和exec()差别
    linux目录中 /usr/local/bin 和 /usr/bin和/usr/local/etc
    mac rar命令相关
    php迭代器
    linux下的find文件查找命令与grep文件内容查找命令
    php 类中的静态属性
    mysql 语句执行顺序
    mysl
    MySQL中concat函数
    animation效果
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10708510.html
Copyright © 2011-2022 走看看