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 }

 

转载于:https://www.cnblogs.com/feiling/p/3242642.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值