47. Permutations II (JAVA)
2024-10-07 05:52:25
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>>();
}
最新文章
- Windows10上安装EDEM2.7
- knockoutjs+ jquery pagination+asp.net web Api 实现无刷新列表页
- Openstack+Kubernetes+Docker微服务实践之路--弹性扩容
- JQuery中的html(),text(),val()区别
- eclipse指定启动的jdk
- Git之使用
- laravel controller:make
- 知识总结: Activity的四种启动模式
- C#里面比较时间大小三种方法
- Spring Cloud App(Service) Pom示例
- 《天书夜读:从汇编语言到windows内核编程》十一 用C++编写内核程序
- lua中怎么替换掉字符串中的$^特殊字符?
- JavaScript正则表达式模式匹配(3)——贪婪模式和惰性模式
- 《java入门第一季》之面向对象(this和super详细分析)
- [luaj]在安卓用使用luaj
- 教女朋友写第一个php
- Shiro的三种授权(十二)
- BeanUtils进行日期格式的拷贝转换
- [C#]Socket通信BeginReceive异步接收数据何时回调Callback
- 热修复 DexPosed AOP Xposed MD
热门文章
- linux cut sort wc sed>;vi awk (文本处理)
- Linux_LVM、RAID_RHEL7
- JS获取URL中参数值
- 【HANA系列】SAP HANA Studio出现";Fetching Children...";问题
- 【MM系列】SAP MM模块-收货自动创建采购订单
- Hello World!----html
- 【Linux开发】Ubuntu图形界面切换与磁盘扩展分区
- 我在拼多多百亿补贴时买了个MAC probook16G苹果笔记本电脑用来写代码,有图有真相,靠谱吗?
- 关于Logcat
- 【扩展事件】跟踪超过3秒的SQL