题目

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].

题解

这道题跟Permutaitons没啥大的区别,就是结果去重。

我之前也有写过去重的两个方法:

一个是在加入结果的时候用contains判断,一个是在找结果的时候看他是不是跟前一个元素相同。

这道题还要考虑的是visited情况,前一个元素就算跟当前元素相同,如果visited==true也没关系。但是如果前面元素跟当前元素相同还没被visited,那么就要做去重处理了。

代码如下:

 1     public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
 2         ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
 3         ArrayList<Integer> item = new ArrayList<Integer>();
 4         
 5         if(num.length==0||num==null)
 6             return res;
 7         boolean[] visited = new boolean[num.length];  
 8         Arrays.sort(num);
 9         permutation_helper(num,res,item,visited);
         return res;
     }
     
     public void permutation_helper(int[] num, ArrayList<ArrayList<Integer>> res, ArrayList<Integer> item,boolean[] visited){
         if(item.size()==num.length){
             res.add(new ArrayList<Integer>(item));
             return;
         }
         
         for(int i = 0; i<num.length;i++){
             if(i>0 && num[i-1] == num[i] && !visited[i-1])
                 continue;
             if(!visited[i]){
                 item.add(num[i]);
                 visited[i]=true;
                 permutation_helper(num,res,item,visited);
                 item.remove(item.size()-1);
                 visited[i]=false;
             }
         }
     }

实验:

如果未加visited判断的话,将会出现下面的错误:

Input: [1,1]
Output: []
Expected: [[1,1]]

因为执行了去重处理,所以一个结果都没有保留

同时,这里在每次添加遍历的item时候,没有判断该元素是否之前被visited过,这样同样会产生重复。

另外一个错误是,for循环的起始是start,而非每次从0开始,这样的话,会忽略掉start位置之前,未visited过的,非重复值。

比如: [1, 2],第一次记录结果[1,2]是正常的没有问题。 但是当退栈到第一个栈,走for循环时,item位置的第一个元素是2, 进入下一层递归,发现start位置是1(0+1),1位置上面是元素2,2被visited过了,所以就结束了这个程序。那么位置在0的,值为1的元素,就被忽略掉了。因为start位置没有从0开始,所以每次都应该从0位置开始。

错误代码如下:

 1     public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
 2         ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
 3         ArrayList<Integer> item = new ArrayList<Integer>();
 4         
 5         if(num == null || num.length == 0)
 6             return res;
 7         //boolean [] visited = new boolean[num.length];
 8         Arrays.sort(num);
 9         permutationhelper(res, num, item, 0);
         return res;
     }
     
     public void permutationhelper(ArrayList<ArrayList<Integer>> res, int[] num, ArrayList<Integer> item, int start){
         if(item.size() == num.length){
             res.add(new ArrayList<Integer>(item));
             return;
         }
         
         for(int i = start; i < num.length; i++){
             if(i > 0 && num[i] == num[i-1])
                 continue;
             
             item.add(num[i]);
             permutationhelper(res, num, item, start+1);
             item.remove(item.size()-1);
         }
     }

为了更清楚的知道整个程序是如何运行的,代码中把start标记标出,正确代码如下:

 1     public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
 2         ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
 3         ArrayList<Integer> item = new ArrayList<Integer>();
 4         
 5         if(num == null || num.length == 0)
 6             return res;
 7         boolean [] visited = new boolean[num.length];
 8         Arrays.sort(num);
 9         permutationhelper(res, num, item, visited, 0);
         return res;
     }
     
     public void permutationhelper(ArrayList<ArrayList<Integer>> res, int[] num, ArrayList<Integer> item, boolean[] visited, int start){
         if(item.size() == num.length){
             res.add(new ArrayList<Integer>(item));
             return;
         }
         
         for(int i = start; i < num.length; i++){
             if(i > 0 && num[i] == num[i-1] && !visited[i - 1])
                 continue;
             if(!visited[i]){
                 item.add(num[i]);
                 visited[i] = true;
                 permutationhelper(res, num, item, visited, start);
                 visited[i] = false;
                 item.remove(item.size()-1);
             }
         }
     }

Permutations II leetcode java的更多相关文章

  1. Permutations II - LeetCode

    目录 题目链接 注意点 解法 小结 题目链接 Permutations II - LeetCode 注意点 不确定有几种排列 解法 解法一:因为有重复的数字所以排列的个数不确定几个,一直生成新的排列直 ...

  2. N-Queens II leetcode java

    题目: Follow up for N-Queens problem. Now, instead outputting board configurations, return the total n ...

  3. Permutations II ——LeetCode

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

  4. Single Number II leetcode java

    问题描述: Given an array of integers, every element appears three times except for one. Find that single ...

  5. Word Break II leetcode java

    题目: Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where e ...

  6. Palindrome Partitioning II Leetcode java

    题目: Given a string s, partition s such that every substring of the partition is a palindrome. Return ...

  7. Remove Duplicates from Sorted List II leetcode java

    题目: Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct ...

  8. Ugly Number II leetcode java

    问题描述: Write a program to find the n-th ugly number. Ugly numbers are positive numbers whose prime fa ...

  9. Word Ladder II leetcode java

    题目: Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) ...

随机推荐

  1. 【mysql】表备份

    几个讲得比较好的资料: http://www.cnblogs.com/liangshaoye/p/5464794.html:讲解了热备,温备,冷备,增量备份,差异备份等多种概念. http://www ...

  2. Java集合(Collection)综述

    1.集合简介 数学定义:一般地,我们把研究对象统称为元素.把一些元素组成的总体叫做集合. java集合定义:集合就是一个放数据的容器,准确的说是放数据对象引用的容器. java中通用集合类存放于jav ...

  3. bind函数详解(转)

    var name = "The Window"; var object = { name: "My Object", getNameFunc: function ...

  4. Chakra调试笔记 TypedArray

    一.TypedArray类型 TypedArray是漏洞中常见到的结构,手册用法有四 1.new TypedArray(length); //byteLength=length * sizeof(Ty ...

  5. TopCoder FlowerGarden【拓扑排序】

    https://community.topcoder.com/stat?c=problem_statement&pm=1918&rd=5006拓扑排序,每次选择最大的就好了 #incl ...

  6. A. 【UR #17】滑稽树上滑稽果

    题解: 首先很显然的是这是一条链(特殊数据说是链是故意让人迷茫的??) 然后 自己就开始yy 觉得每一次是加入一个使得当前值最小的数 然而这tm又是特殊数据?? 那就写一波发现是错的 考虑一下特殊数据 ...

  7. [JSOI2009]等差数列

    链接:http://www.lydsy.com/JudgeOnline/problem.php?id=1558 题解: 考虑这么用线段树进行维护,由于他有区间修改等差数列 很容易想到可以用差分数组来维 ...

  8. class path resource [spring/applicationContext.xml] cannot be opened because it does not exist

    1.查看路径有没有写错 2.编辑器认为你的文件不是 source folders(原文件),需要你手动将文件改过来

  9. java加密工具类,可设置对应的加解密key

    public class AesEncryptUtil { //使用AES-128-CBC加密模式,key需要为16位,key和iv可以相同! private static String KEY =& ...

  10. L3-020 至多删三个字符 (30 分) 线性dp

    给定一个全部由小写英文字母组成的字符串,允许你至多删掉其中 3 个字符,结果可能有多少种不同的字符串? 输入格式: 输入在一行中给出全部由小写英文字母组成的.长度在区间 [4, 1] 内的字符串. 输 ...