47. 全排列 II
给定一个可包含重复数字的序列,返回所有不重复的全排列。
示例:
输入: [1,1,2]
输出:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
递归法解决包含重复数字的全排列
class Solution {
//去掉重复的排列:只需要增加一个判断数组中元素是否重复的函数即可。
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
permutationUnique(list, nums, 0);
return list;
}
//方法功能:对字符串中字符/元素进行全排列
//参数list存放所有全排列结果,数组nums存放待排序元素,start为待排序的元素集合所在数组中第一个位置
public void permutationUnique(List<List<Integer>> list, int []nums, int start) {
if(nums == null || start < 0) {
return ;
}
if(start == nums.length - 1) {
//完成一次全排列,添加当前排列的结果到最后的集合中
List<Integer> tmpList = Arrays.stream(nums).boxed().collect(Collectors.toList());
list.add(tmpList);
} else {
for(int i = start; i < nums.length; i++) {
//判断待排列的数组元素中是否有重复
if(!isDuplicated(nums, start, i)) {
continue;
}
//交换start和i所在位置的元素
swap(nums, start, i);
//固定第一个字符,对剩余的元素进行全排列
permutationUnique(list, nums, start + 1);
//还原start和i所在的位置
swap(nums, start, i);
}
}
}
//方法功能:交换字符数组下表为start,j对应的元素
public void swap(int []nums, int start, int i) {
int temp = nums[start];
nums[start] = nums[i];
nums[i] = temp;
}
//方法功能:判断【begin,end)区间中是否有元素与*end相等
//输入参数:begin和end为指向元素的指针
//返回值:true:如果有相等的元素,负责返回false
public boolean isDuplicated(int []str, int begin, int end) {
for(int i = begin; i < end; i++) {
if(str[i] == str[end]) {
return false;
}
}
return true;
}
}