LeetCode 047 Permutations II
2014-03-23 21:40
323 查看
题目
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
and
数组全排列,数组中可能有数字重复。
思路
1 基础的解法,TLE,可以想到会有内容重复计算。
2 这里考虑一个新的方法,先排序让从小到大。这样用了O(nlgn),这样有重复的也只能出现在相邻。之后,需要一个数组,来记录相应的元素是否使用过。一旦未使用过,且和前面的元素相同,那么就可以跳过这个元素的dfs。
代码
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].
数组全排列,数组中可能有数字重复。
思路
1 基础的解法,TLE,可以想到会有内容重复计算。
2 这里考虑一个新的方法,先排序让从小到大。这样用了O(nlgn),这样有重复的也只能出现在相邻。之后,需要一个数组,来记录相应的元素是否使用过。一旦未使用过,且和前面的元素相同,那么就可以跳过这个元素的dfs。
代码
public class Solution { public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) { ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> tmp = new ArrayList<Integer>(); int n = num.length; boolean[] visited = new boolean ; Arrays.sort(num); permuteImp(res, tmp, num, visited); return res; } private void permuteImp(ArrayList<ArrayList<Integer>> res, ArrayList<Integer> tmp, int[] num, boolean[] visited){ if(tmp.size() == num.length){ res.add(new ArrayList<Integer>(tmp)); return; } for(int i=0; i<num.length; i++){ if(visited[i]==false){ if(i>0&&num[i-1]==num[i]&&visited[i-1]==false){ continue; } tmp.add(num[i]); visited[i] = true; permuteImp(res, tmp, num, visited); visited[i] = false; tmp.remove(tmp.size()-1); } } } }
相关文章推荐
- leetcode 047 —— Permutations II
- Java for LeetCode 047 Permutations II
- LeetCode 047 Permutations II
- LeetCode 047 Permutations II
- leetcode 047 Permutations II
- leetcode解题方案--047--Permutations II
- [LeetCode]047-Permutations II
- [LeetCode]题解(python):047-Permutations II
- [leetcode] Permutations II
- leetcode-47-Permutations II 搜索-剪枝
- 【LeetCode】Permutations II
- leetCode 47.Permutations II (排列组合II) 解题思路和方法
- [LeetCode] Permutations II
- [Leetcode 101] 47 Permutations II
- [LeetCode]Permutations II
- LeetCode - Permutations II
- [LeetCode] Permutations II 解题报告
- [LeetCode] Permutations II 解题报告
- [Leetcode] Permutations II
- [leetcode] 47.Permutations II