Permutations II
来源:互联网 发布:mysql可视化工具使用 编辑:程序博客网 时间:2024/05/29 03:17
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], [2,1,1]]
这类的题还是有固定的格式的。首先要明确是一道写dfs的题。跟permutation i 不一样,如果也用swap的方式,有的情况是不能够避免重复的,所以参考了网上之后还是采用设置visited[nums.length]的这种方式,每次递归在数组里边取一个还没有被选过的元素,如果出现相同元素,那么需要保证它前面的那个元素已经使用过了,否则它使用的时候,一定会跟前面的那个元素组成的情况会有重复。
代码:
public List<List<Integer>> permuteUnique(int[] nums) { List<List<Integer>> result = new ArrayList<>(); if(nums == null || nums.length ==0) return result; Arrays.sort(nums); List<Integer> cur = new ArrayList<>(); boolean [] visited = new boolean[nums.length]; dfs(result, cur, visited, nums); return result; } public void dfs( List<List<Integer>> result, List<Integer> cur, boolean [] visited, int[] nums){ if(cur.size() == nums.length){ result.add( new ArrayList<>(cur)); return; } for(int i=0;i<nums.length;i++){ if(visited[i] == true || (i>0 && nums[i] == nums[i-1] && visited[i-1] == false)){ continue; } visited[i] = true; cur.add(nums[i]); dfs(result, cur, visited, nums); cur.remove(cur.size()-1); visited[i] = false; } }
0 0
- 【LeetCode】Permutations && Permutations II
- leetcode: Permutations/Permutations II
- leetcode Permutations & Permutations II
- [Leetcode]Permutations && Permutations II
- Permutations and Permutations II
- Permutations && Permutations ii
- Permutations II
- Permutations II
- Permutations II
- Permutations II
- Permutations II
- Permutations II
- Permutations II
- Permutations II
- Permutations II
- Permutations II
- Permutations II
- Permutations II
- Elasticsearch、Fluentd与Kibana:开源的日志搜索与可视化方案
- AC3/EAC3格式总结
- Linux 守护进程的启动方法
- hdoj-5969-最大的位或
- VC++内存泄漏的检测与定位
- Permutations II
- ICA独立成分分析
- 华信IT教育201611第一篇博客
- jquery.slimscroll.js兼容firefox和动态高度计算
- C++笔记2
- centos6.5安装python3
- 设计模式之--命令
- 非凸问题寻优
- HTML开发-基本代码规范