【leetcode刷题笔记】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].


 

题解:跟Permutation差不多,只是这次会有重复的元素,如下图所示,如果只用DFS的话就会产生重复的排列:

上图中括号内的数字代表这个1是序列中第几个1。上述DFS产生了两个112,121和211。我们可以把两个112写成:1(1) 1(2) 2和1(2) 1(1) 2,可以看到,产生重复的原因是我们其实并不区分当前的1是序列中的第几个1,所以如果我们可以保证序列中相同的元素只按照在序列中序号递增的顺序出现,就可以避免重复了。比如上述的112,我们只允许1(1) 1(2) 2这种情况,而步允许1(2) 1(1) 2这种情况出现。

只需要在判断的时候加上如下所示高亮部分的代码就可以做到这一点:

 1 public class Solution {
 2     public List<List<Integer>> permuteUnique(int[] num) {
 3         List<List<Integer>> answerList = new ArrayList<List<Integer>>();
 4         ArrayList<Integer> currentList = new ArrayList<Integer>();
 5         boolean[] visited = new boolean[num.length];
 6         
 7         Arrays.sort(num);
 8         DS(answerList, visited, num, currentList);        
 9         return answerList;
10     }
11     
12     public void DS(List<List<Integer>> answerList,boolean[] visited,int[] num,ArrayList<Integer> currentList){
13         boolean find = true;
14         for(int i = 0;i < num.length;i++){
15             if(i-1>=0 && num[i]== num[i-1] && visited[i-1] == false)
16                 continue;
17             if(!visited[i]){
18                 currentList.add(num[i]);
19                 visited[i]= true;
20                 DS(answerList, visited, num, currentList);
21                 visited[i]= false;
22                 currentList.remove(currentList.size()-1);
23                 find = false;
24             }
25         }
26         if(find){
27             ArrayList <Integer> temp = new ArrayList<Integer>(currentList);
28             answerList.add(temp);
29         }
30     }
31 }
posted @ 2014-07-22 17:15  SunshineAtNoon  阅读(183)  评论(0编辑  收藏  举报