一 题目
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] ]
Accepted 274,348 Submissions 649,111
二 分析
求可能重复数组的排列,medium级别。跟上个题目 leetcode 46. Permutations 类似。这个题目是可能重复的。
所以使用bool 数组记录是否使用过。基本思路沿用之前的递归。
public static List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
ArrayList<Integer> list = new ArrayList<>();
boolean[] used = new boolean[nums.length];
helper(nums,list, res,used);
return res;
}
//递归2 插入法
private static void helper( int[] nums, ArrayList<Integer> list, List<List<Integer>> res ,boolean[] used){
if(list.size() == nums.length){//到达结尾,实现全排序
if(!res.contains(list)){
res.add(new ArrayList<>(list));
}
return;
}
for(int i=0;i<nums.length;i++){
//不重复的
if(!used[i] ){
used[i] = true;
list.add(nums[i]);//插入
helper(nums,list,res,used);
list.remove(list.size()-1);//删除
used[i] = false;
}
}
}
Runtime: 233 ms, faster than 5.01% of Java online submissions forPermutations II.
Memory Usage: 38.1 MB, less than 98.51% of Java online submissions forPermutations II.
太慢了,优化下:对于[1,1,2]。在helper首遍历时,1 作为首元素被加到list中,并进行后续元素的添加;那么,当helper跑完第一个分支,遍历到1 (第二个)时,这个1 不再作为首元素添加到list中,另外,需要对给定的序列nums进行排序,使得大小相同的元素排在一起。 所以修正后代码如下:
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
ArrayList<Integer> list = new ArrayList<>();
boolean[] used = new boolean[nums.length];
Arrays.sort(nums);
helper(nums,list, res,used);
return res;
}
//递归2 插入法
private static void helper( int[] nums, ArrayList<Integer> list, List<List<Integer>> res ,boolean[] used){
if(list.size() == nums.length){//到达结尾,实现全排序
if(!res.contains(list)){
res.add(new ArrayList<>(list));
}
return;
}
for(int i=0;i<nums.length;i++){
//重复的
if(used[i] ){
continue;
}
//前一个是
if(i > 0 &&!used[i-1]&&(nums[i]== nums[i-1])){
continue;
}
used[i] = true;
list.add(nums[i]);//插入
helper(nums,list,res,used);
list.remove(list.size()-1);//删除
used[i] = false;
}
}
}
Runtime: 10 ms, faster than 18.30% of Java online submissions forPermutations II.
Memory Usage: 39.4 MB, less than 65.67% of Java online submissions forPermutations II.
还不快。看了网上大神的,把res加入结果前判断去掉了,因为已经排序过了。
private static void helper(int[] nums, ArrayList<Integer> list, List<List<Integer>> res, boolean[] used) {
if (list.size() == nums.length) {// 到达结尾,实现全排序
res.add(new ArrayList<>(list));
return;
}
for (int i = 0; i < nums.length; i++) {
// 不重复的
if (used[i]) {
continue;
}
// 前一个是
if (i > 0 && !used[i - 1] && (nums[i] == nums[i - 1])) {
continue;
}
used[i] = true;
list.add(nums[i]);// 插入
helper(nums, list, res, used);
list.remove(list.size() - 1);// 删除
used[i] = false;
}
}
Runtime: 1 ms, faster than 100.00% of Java online submissions forPermutations II.
Memory Usage: 39.2 MB, less than 73.13% of Java online submissions forPermutations II.