【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 @   SunshineAtNoon  阅读(183)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示