[LeetCode]Permutations II
来源:互联网 发布:数据充值 编辑:程序博客网 时间:2024/05/15 01:36
Question
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]
]
本题难度Medium。
【复杂度】
时间 O(N!) 空间 O(N)
【思路】
与Permutations不一样的地方就是有duplicates。办法就是跳过duplicates(29-33行)。其他不变。
【代码】
public class Solution { public List<List<Integer>> permuteUnique(int[] nums) { //require List<List<Integer>> ans=new ArrayList<>(); if(nums==null) return ans; int size=nums.length; if(size<1) return ans; List<Integer> list=new ArrayList<Integer>(),remains=new ArrayList<Integer>(); for(int n:nums) remains.add(n); //invariant helper(list,remains,ans); //ensure return ans; } private void helper(List<Integer> preList,List<Integer> remains,List<List<Integer>> ans){ //bound if(remains.size()==0){ List<Integer> list=new ArrayList<Integer>(preList); ans.add(list); return; } Set<Integer> set=new HashSet<Integer>(); for(int i=0;i<remains.size();i++){ int n=remains.get(0); if(set.contains(n)){ remains.remove(0); remains.add(n); continue; } set.add(n); remains.remove(0); preList.add(n); helper(preList,remains,ans); remains.add(n); preList.remove(preList.size()-1); } }}
参考
[LeetCode]Permutations
0 0
- 【LeetCode】Permutations && Permutations II
- leetcode: Permutations/Permutations II
- leetcode Permutations & Permutations II
- [Leetcode]Permutations && Permutations II
- Leetcode: Permutations and Permutations II
- leetcode-permutations and permutations II
- Leetcode:Permutations与Permutations II
- LeetCode: Permutations II
- LeetCode Permutations II
- LeetCode: Permutations II
- [Leetcode] Permutations II
- [LeetCode] Permutations II
- [Leetcode] Permutations II
- leetcode Permutations II
- [LeetCode]Permutations II
- leetcode - Permutations II
- LeetCode-Permutations II
- [leetcode] Permutations II
- 业务逻辑层接口设计
- jquery 仿锚点跳转到页面指定位置
- 浅谈Android Studio 中Gradle的使用方法
- 【C语言】任意进制之间的转换(支持小数部分)
- Spring实现AOP的4种方式
- [LeetCode]Permutations II
- Android下载网址收集(整理中)
- java 集合汇总
- Android 调用系统拍照后返回的图片变小了(变模糊了)
- Android的log保存到文件上查看
- 自定义Android IOC框架
- 【我的Java课-1】if 与 else 语句
- 常用性能分析工具之perf,strace
- android studio 提示没有找到apt