Permutation II @leetcode
来源:互联网 发布:2016剑网三男神脸数据 编辑:程序博客网 时间:2024/05/16 02:01
转自:http://www.cnblogs.com/longhorn/p/3527824.html
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]
.
有重复数字的话,用递归就不是很好做。每一次产生一个结果就要判断这个结果是否已经包含在result中,所以时间长。
用dfs做的话用两个地方需要注意。
一个是要对字符串进行排序。因为如果排序的话,可以很好避免因为重复数字产生的重复的情况。
第二个就是如何避免因为重复数字产生的重复情况。因为已经排好序,所以每次选择下一个数字的时候只要避免和之前的数字重复就行。
比如[1,2,3,3,4].当我们产生[1,2,3]的时候,我们只要避免回溯的时候再次选择3,从而产生[1,2,3]就行了。
public class Solution { public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) { Arrays.sort(num); boolean[] visited = new boolean[num.length]; ArrayList<Integer> tmp = new ArrayList<Integer>(); ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); permute2(num, visited, tmp, result); return result; } public static void permute2(int[] num, boolean[] visited, ArrayList<Integer> tmp, ArrayList<ArrayList<Integer>> result) { if (tmp.size() == num.length) { result.add(new ArrayList<Integer>(tmp)); return; } for (int i=0; i<num.length; i++) { if (visited[i] == false) { tmp.add(num[i]); visited[i] = true; permute2(num, visited, tmp, result); visited[i] = false; tmp.remove(tmp.size()-1); <span style="background-color: rgb(255, 0, 0);"> while (i<num.length-1 && num[i] == num[i+1]) i++;</span> } } }}
0 0
- LeetCode之Permutation、Permutation II
- leetcode -- Permutation & Permutation II--重点
- [Leetcode] Permutation II
- Leetcode Permutation I & II
- Leetcode Permutation II
- Permutation II @leetcode
- [LeetCode] Permutation II
- Leetcode -- Permutation II
- Permutation II--LeetCode
- 47. Permutation II Leetcode Python
- [LeetCode 267] Palindrome Permutation II
- LeetCode 267. Palindrome Permutation II
- LeetCode 267. Palindrome Permutation II
- Leetcode Palindrome Permutation I & II
- [LeetCode] Next Permutation、Permutations、Permutations II、Permutation Sequence
- 【leetcode 排列组合问题】Next Permutation | Permutations | Permutations II | Permutation Sequence
- LeetCode 题解(242) : Palindrome Permutation II
- [leetcode] 267. Palindrome Permutation II 解题报告
- android QC Memory Map
- const的用法,特别是用在函数前面与后面的区别!
- osgi实战学习之路:5.生命周期及利用命令、装饰者模式实现基于socket交互Bundle命令demo
- Win8.1应用开发之离线缓存
- xyoj 2124:珍惜现在,感恩生活
- Permutation II @leetcode
- UVA 1558 - Number Game(博弈dp)
- mini2440 蜂鸣器驱动
- Win版Chrome或加速电池损耗
- android中app的更新案例
- onInterceptTouchEvent(MotionEvent)与OnTouchEvent方法分析
- 《论语》学习摘要第一篇
- C#03
- ARM指令