Permutations II
2015-07-24 20:55
288 查看
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].
这个方法同样可以解决Permutations问题,更改其中的ArrayList为HashSet即可。
思路类似:list加入1,2加入1前,1后,list变为1,2;和2,1;同理插入3,list变为
3,1,2;1,3,2;1,2,3;3,2,1;2,3,1;2,1,3;
For example,
[1,1,2] have the following unique permutations:
[1,1,2], [1,2,1], and [2,1,1].
这个方法同样可以解决Permutations问题,更改其中的ArrayList为HashSet即可。
思路类似:list加入1,2加入1前,1后,list变为1,2;和2,1;同理插入3,list变为
3,1,2;1,3,2;1,2,3;3,2,1;2,3,1;2,1,3;
public static ArrayList<ArrayList<Integer>> permuteUnique(int[] num) { ArrayList<ArrayList<Integer>> returnList = new ArrayList<ArrayList<Integer>>(); returnList.add(new ArrayList<Integer>()); for (int i = 0; i < num.length; i++) { HashSet<ArrayList<Integer>> currentSet = new HashSet<ArrayList<Integer>>(); for (List<Integer> l : returnList) { for (int j = 0; j < l.size() + 1; j++) { l.add(j, num[i]); ArrayList<Integer> T = new ArrayList<Integer>(l); l.remove(j); currentSet.add(T); } } returnList = new ArrayList<ArrayList<Integer>>(currentSet); } return returnList; }
相关文章推荐
- poj2342.Anniversary party(树形dp)
- Hdu5303 Delicious Apples 贪心
- struts2 模型分配问题和延迟加载问题
- cocos2d-x 3.4 VS2013无法打开包含文件extensions/ExtensionExport.h
- 首篇技术博客感想
- UVa 11361 Investigating Div-Sum Property 数字和与倍数
- 共享一个以前写的俄罗斯方块
- 数据库事物隔离级别通俗理解
- Universal-Image-Loader分析 第一篇
- 士兵队列
- AngularJs编写指令
- ubuntu android studio 安装
- 了解NoSQL
- poj 3126 Prime Path (bfs)
- 食物链
- HDU 3681 Prison Break(状压DP + 二分)
- hdu 4266 The Worm in the Apple (线段树)
- 树的重心
- treap 模板
- 【C++系列】之 运算符重载