1.题目:
给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。
示例 1:
输入:nums = [1,1,2] 输出: [[1,1,2], [1,2,1], [2,1,1]] 示例 2:
输入:nums = [1,2,3] 输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/permutations-ii 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.代码:
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
boolean[] used;
public List<List<Integer>> permuteUnique(int[] nums) {
used = new boolean[nums.length];
Arrays.sort(nums);//记得要排序
backTracking(nums);
return result;
}
public void backTracking(int[] nums){
if(nums.length==path.size()) {
result.add(new ArrayList<>(path));
return;
}
for(int i=0; i<nums.length; i++){
//这两步都是去重
if(used[i]){
continue;
}
if(i>0 && nums[i]==nums[i-1] && used[i-1]==false){
continue;//树层去重
}
path.add(nums[i]);
used[i]=true;
backTracking(nums);
path.remove(path.size()-1);
used[i]=false;
}
}
}