1.给定一个可包含重复数字的序列 nums
,按任意顺序 返回所有不重复的全排列。
2.此题与 LeetCode 46.全排列相似,但46题中元素不重复,47题中含有重复元素.
3.解题方法 ; 递归 + 哈希表
4.解题思路: 首先创建全局变量 retList 来准备存储所有全排列数组
创建 helper 方法,用来递归
:
返回 retList ;
5.具体代码如下:
List<List<Integer>> retList = new LinkedList<>();
public List<List<Integer>> permuteUnique(int[] nums) {
// 借助 permute2Helper() 方法完成递归
// 首先传入的count 为 0(从 0 开始交换)
permute2Helper(0,nums);
return retList;
}
private void permute2Helper(int count, int[] nums) {
// 当count 换到最后一个时.说明一轮已经完成,记录到最终结果中
if(count + 1 == nums.length){
List<Integer> tmpList = new LinkedList<>();
for (int i = 0; i < nums.length; i++) {
tmpList.add(nums[i]);
}
retList.add(tmpList);
}
// 使用 HashSet 去重
Set<Integer> set = new HashSet<>();
for (int i = count; i < nums.length; i++) {
// 添加成功,说明钙元素还未使用,if代码块
if(set.add(nums[i])){
swap(nums,count,i);
permute2Helper(count + 1,nums);
swap(nums,count,i);
}
}
}
// 帮助完成交换
private void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
此题考点: 1.递归终止条件;
2.递归的理解;
3.怎样去重.