Given a collection of numbers that might contain duplicates, return all possible unique permutations.

Example:

Input: [1,1,2]
Output:
[
[1,1,2],
[1,2,1],
[2,1,1]
]

有重复数字的情况,之前在Subsets II,我们采取的是在某一个递归内,用for循环处理所有重复数字。这里也相同,需要在递归内考虑重复数字,重复数字只能插入在已插入的重复数字之前,碰到相同的数字,即停止循环,退出递归。

class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<Integer> ans = new ArrayList<Integer>();
if(nums.length == 0) return ret; ans.add(nums[0]);
insertNum(nums, 1, ans);
return ret;
} public void insertNum(int[] nums, int index, List<Integer> ans){
if(index == nums.length) {
List<Integer> new_ans = new ArrayList<Integer>(ans);
ret.add(new_ans);
return;
} for(int j = 0; j < ans.size(); j++){ //iterate all possible insert position
ans.add(j,nums[index]);
insertNum(nums, index+1, ans);
ans.remove(j); //recover if(ans.get(j)==nums[index] ) return; //avoid repeat, 重复的数字只能添加在已有数字之前
}
//insert in the back
ans.add(nums[index]);
insertNum(nums, index+1, ans);
ans.remove(ans.size()-1); //recover
} private List<List<Integer>> ret = new ArrayList<List<Integer>>();
}

最新文章

  1. Windows10上安装EDEM2.7
  2. knockoutjs+ jquery pagination+asp.net web Api 实现无刷新列表页
  3. Openstack+Kubernetes+Docker微服务实践之路--弹性扩容
  4. JQuery中的html(),text(),val()区别
  5. eclipse指定启动的jdk
  6. Git之使用
  7. laravel controller:make
  8. 知识总结: Activity的四种启动模式
  9. C#里面比较时间大小三种方法
  10. Spring Cloud App(Service) Pom示例
  11. 《天书夜读:从汇编语言到windows内核编程》十一 用C++编写内核程序
  12. lua中怎么替换掉字符串中的$^特殊字符?
  13. JavaScript正则表达式模式匹配(3)——贪婪模式和惰性模式
  14. 《java入门第一季》之面向对象(this和super详细分析)
  15. [luaj]在安卓用使用luaj
  16. 教女朋友写第一个php
  17. Shiro的三种授权(十二)
  18. BeanUtils进行日期格式的拷贝转换
  19. [C#]Socket通信BeginReceive异步接收数据何时回调Callback
  20. 热修复 DexPosed AOP Xposed MD

热门文章

  1. linux cut sort wc sed&gt;vi awk (文本处理)
  2. Linux_LVM、RAID_RHEL7
  3. JS获取URL中参数值
  4. 【HANA系列】SAP HANA Studio出现&quot;Fetching Children...&quot;问题
  5. 【MM系列】SAP MM模块-收货自动创建采购订单
  6. Hello World!----html
  7. 【Linux开发】Ubuntu图形界面切换与磁盘扩展分区
  8. 我在拼多多百亿补贴时买了个MAC probook16G苹果笔记本电脑用来写代码,有图有真相,靠谱吗?
  9. 关于Logcat
  10. 【扩展事件】跟踪超过3秒的SQL