​官方详细题解​

47. 全排列 II_java

class Solution {


public List<List<Integer>> permuteUnique(int[] nums) {
int len = nums.length;
List<List<Integer>> res = new ArrayList<>();
if (len == 0) return res;

Deque<Integer> path = new ArrayDeque<>();
int n = nums.length;
boolean[] used = new boolean[n];
Arrays.sort(nums); // 排序, 以保证相等的元素相邻
dfs(nums, used, 0, n, path, res);
return res;
}

public void dfs(int[] nums, boolean[] used, int cur, int n, Deque<Integer> path, List<List<Integer>> res) {
if (cur == n) {
res.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < n; i++) {
// 判重, 若使用过该元素则跳过
if (used[i])
continue;

// 剪枝条件:i > 0 是为了保证 nums[i - 1] 有意义
// 写 !used[i - 1] 是因为 nums[i - 1] 在深度优先遍历的过程中刚刚被撤销选择

作者:liweiwei1419
链接:https://leetcode-cn.com/problems/permutations-ii/solution/hui-su-suan-fa-python-dai-ma-java-dai-ma-by-liwe-2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1])
continue;
path.addLast(nums[i]);
used[i] = true;
// 进入下一层
dfs(nums, used, cur + 1, n, path, res);
// 恢复原来状态
path.removeLast();
used[i] = false;
}
}
}