zoukankan      html  css  js  c++  java
  • [leetcode]PermutationsII

    Permutations II

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

    For example,
    [1,1,2] have the following unique permutations:
    [1,1,2][1,2,1], and [2,1,1].

    算法思路:

    [leetcode]Permutations 类似,只是需要加一步去重,如何去重?

    思路1:

    第一次做,把list转换成了String类型,再根据string的equals方法去重,弱爆了。

    思路2:

    将num排序,进行dfs时候,遇到后继节点与前驱相同,则跳过后继节点。

    代码如下:

     1 public class Solution {
     2     List<List<Integer>> result = new ArrayList<List<Integer>>();
     3     public List<List<Integer>> permuteUnique(int[] num) {
     4         if(num== null || num.length == 0) return result;
     5         Arrays.sort(num);
     6         Set<Integer> set = new HashSet<Integer>();
     7         List<Integer> list = new ArrayList<Integer>();
     8         dfs(list,set,num);
     9         return result;
    10     }
    11     private void dfs(List<Integer> list,Set<Integer> set,int[] num){
    12         if(list.size() == num.length){
    13             result.add(new ArrayList<Integer>(list));
    14             return;
    15         }
    16         for(int i = 0 ; i < num.length; i++){
    17             if(set.contains(i)) continue;
    18             list.add(num[i]);
    19             set.add(i);
    20             dfs(list, set, num);
    21             set.remove(i);
    22             list.remove(list.size() - 1);
    23             while(i + 1 < num.length && num[i] == num[i + 1])
    24                 i++;
    25         }
    26     }
    27 }
  • 相关阅读:
    数据结构-串的堆分配存储
    ServerSocket
    Java-坦克大战
    Java-输入输出流
    MyEclipse 快捷键
    数据结构-串的定长顺序存储
    我的软考资料集合
    软考中级软件设计师考试大纲
    2016年第一季度阅读书目
    中国大陆开源镜像网站汇总
  • 原文地址:https://www.cnblogs.com/huntfor/p/3863548.html
Copyright © 2011-2022 走看看