[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 }

posted on 2014-07-23 17:25  喵星人与汪星人  阅读(287)  评论(0编辑  收藏  举报