[LeetCode]Permutations II
2016-10-18 16:48
288 查看
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行)。其他不变。
【代码】
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相关文章推荐
- Leetcode: Permutations II
- [LeetCode] Permutations II
- leetcode 47. Permutations II
- LeetCode 47. Permutations II(生成不同的组合-dfs)
- 【LeetCode-47】Permutations II
- LeetCode 047 Permutations II
- [leetCode刷题笔记]47. Permutations II
- LeetCode: Permutations II
- 【LeetCode】Permutations II
- LeetCode (Permutations II)
- [LeetCode] Permutations II 解题报告
- leetcode 46-Permutations and 47-Permutations II
- exceptionfunction[LeetCode]Permutations II
- LeetCode: Permutations II 解题报告
- leetcode- Permutations II
- 【Leetcode】Permutations II
- leetcode 46-Permutations and 47-Permutations II
- LeetCode - Permutations II
- Leetcode_Permutations II
- LeetCode 47. Permutations II(排列)