• leetcode -- Permutations II TODO


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

    解题思路:

    Permutations 那题输入是不包含重复元素的,故生成的排列都是不同的,II中输入元素可能相同

    因而可能会产生相同的排列,这里需要去重,没有找到很好的剪枝条件,这里使用HashSet来去重,

    当发现已经添加过该组合则不会再添加

    public boolean add(E e)
        如果此 set 中尚未包含指定元素,则添加指定元素。
        更确切地讲,如果此 set 没有包含满足 (e==null ? e2==null : e.equals(e2)) 的元素 e2,则向此 set 添加指定的元素 e。
        如果此 set 已包含该元素,则该调用不更改 set 并返回 false
     1 public class Solution {
     2     public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         int len = num.length;
     6         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
     7         HashSet<ArrayList<Integer>> tmp = new HashSet<ArrayList<Integer>>();
     8         //Arrays.sort(num);
     9         permutation(num, 0, len, result, tmp);
    10         return result;
    11     }
    12     
    13     public void permutation(int[] num, int depth, int len,
    14         ArrayList<ArrayList<Integer>> result, HashSet<ArrayList<Integer>> tmpResult){
    15         if(depth == len){
    16             ArrayList<Integer> per = new ArrayList<Integer>();
    17             for(int i =0 ; i < len; i++)
    18                 per.add(num[i]);
    19             
    20             if(tmpResult.add(per))
    21                 result.add(per);
    22         }
    23         
    24         for(int i = depth; i < len; i++) {
    25             //if(i != depth && num[i] == num[depth])
    26             //    continue;
    27             
    28             int tmp = num[i];
    29             num[i] = num[depth];
    30             num[depth] = tmp;
    31             
    32             permutation(num, depth + 1, len, result, tmpResult);
    33             
    34             tmp = num[i];
    35             num[i] = num[depth];
    36             num[depth] = tmp;
    37         }
    38     }
    39 }
  • 相关阅读:
    Eclipse常用插件汇总
    关于销售订单
    java下载文件的种方式
    左右对联
    链表
    Spring MVC 入门
    JAVA环境配置总结
    struts2 iterator判断奇偶
    保存页面的浏览记录
    心扬JS分页
  • 原文地址:https://www.cnblogs.com/feiling/p/3242642.html
Copyright © 2020-2023  润新知