LeetCode: 47. 全排列 II
超时代码
List<List<Integer>> list = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
final int maxInt = Integer.MAX_VALUE;
public List<List<Integer>> permuteUnique(int[] nums) {
getRes(nums, temp);
return list;
}
public void getRes(int[] nums, List<Integer> t){
if(t.size() == nums.length){
for (List<Integer> lis: list) {
if(lis.hashCode() == t.hashCode()){
return ;
}
}
list.add(new ArrayList<>(t));
return ;
}
for (int i = 0; i < nums.length; i++) {
if(nums[i] != maxInt){
temp.add(nums[i]);
nums[i] = maxInt;
getRes(nums, temp);
nums[i] = temp.remove(temp.size() - 1);
}
}
return ;
}
提交代码
class Solution {
// 1 1 2
List<List<Integer>> list = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
String str = "";
final int maxInt = Integer.MAX_VALUE;
public List<List<Integer>> permuteUnique(int[] nums) {
getRes(nums, temp);
return list;
}
public void getRes(int[] nums, List<Integer> t){
if(t.size() == nums.length){
if(str.contains(t.toString())){ return ; }
list.add(new ArrayList<>(t));
str += t.toString();
return ;
}
for (int i = 0; i < nums.length; i++) {
if(nums[i] != maxInt){
temp.add(nums[i]);
nums[i] = maxInt;
getRes(nums, temp);
nums[i] = temp.remove(temp.size() - 1);
}
}
return ;
}
}
优化
List<List<Integer>> list = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
private final int maxInt = Integer.MAX_VALUE;
public List<List<Integer>> permuteUnique(int[] nums) {
// 排序
Arrays.sort(nums);
getRes(nums, temp);
return list;
}
public void getRes(int[] nums, List<Integer> t) {
if (t.size() == nums.length) {
list.add(new ArrayList<>(t));
return;
}
for (int i = 0; i < nums.length; i++) {
// 剪枝条件
if (nums[i] == maxInt || (i > 0 && nums[i] == nums[i - 1] && nums[i - 1] != maxInt)) {
continue;
}
//if(nums[i] != maxInt)
temp.add(nums[i]);
nums[i] = maxInt;
getRes(nums, temp);
// 递归回溯
nums[i] = temp.remove(temp.size() - 1);
}
return;
}
public static void main(String[] args) {
int[] n = {3, 3, 0, 3};
Daily47 d = new Daily47();
List<List<Integer>> lists = d.permuteUnique(n);
System.out.println(Arrays.toString(lists.toArray()));
}