1)数字不能重复使用(同一树枝不能重复)
使用used辅助数组,使用就改为true
2)排列不可重复(同一树层不可重复)
if (i >0 &&nums[i] == nums[i-1] && used[i-1] == false){
//used[i-1] == false 说明同一数层使用过
//used[i] == true 说明同一树枝使用过
continue;
}
i>0是防止数组索引i-1越界
3)整体代码
public static void main(String[] args) {
int nums[] = {1,1,2};
System.out.println(new T01().permuteUnique(nums));
}
//给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new LinkedList<>();
boolean[] used = new boolean[nums.length];
dfs(nums, res, path, used);
return res;
}
private void dfs(int[] nums, List<List<Integer>> res, List<Integer> path, boolean[] used) {
if (path.size() == nums.length){
res.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; i++) {
if (i >0 &&nums[i] == nums[i-1] && used[i-1] == false){
//used[i-1] == false 说明同一数层使用过
//used[i] == true 说明同一树枝使用过
continue;
}
if (used[i] == false){
path.add(nums[i]);
used[i] = true;//标记为使用过
dfs(nums, res, path, used);
path.remove(path.size()-1);
used[i] = false;
}
}
}