思路
这个题和上一题的全排列不同的地方是有重复的数字。需要去重,这里去重有两种方法:一个是用set去重,一个将数组排序然后用used数组去重。
重点说下用used数组去重:
因为是排列问题,所以就要用used数组记录遍历的元素,而去重刚好也要记录遍历的元素,所以就二者合二为一了。
首先对数组进行排序,当一个元素没有被使用的时候usede是false,被使用过后就是true,所以当nums[i-1] == nums[i] && used[i-1]==false时,表明该元素在水平方向上已经使用过了。所以水平方向后面的元素不在使用,但是垂直方向可以使用。
代码
方法一:set去重
class Solution {
Set<List<Integer>> res = new HashSet<>();
List<Integer> path = new ArrayList<>();
int[] usedNums = new int[31];
public List<List<Integer>> permuteUnique(int[] nums) {
boolean[] used = new boolean[nums.length];
fun(nums,used);
return new ArrayList(res);
}
public void fun(int[] nums,boolean[] used){
if(nums.length == path.size()){
res.add(new ArrayList(path));
return;
}
usedNums = new int[31];
for(int i = 0;i<nums.length;i++){
if(used[i] == true){
continue;
}
path.add(nums[i]);
used[i] = true;
fun(nums,used);
path.remove(path.size()-1);
used[i] = false;
}
}
}
方法二:used数组去重
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> permuteUnique(int[] nums) {
boolean[] used = new boolean[nums.length];
Arrays.sort(nums);
fun(nums,used);
return res;
}
public void fun(int[] nums,boolean[] used){
if(nums.length == path.size()){
res.add(new ArrayList(path));
return;
}
for(int i = 0;i<nums.length;i++){
if(i>0 && nums[i-1] == nums[i] && used[i-1] == false){
continue;
}
if(used[i] == false){
path.add(nums[i]);
used[i] = true;
fun(nums,used);
path.remove(path.size()-1);
used[i] = false;
}
}
}
}