来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
编号47. 全排列2 剪枝
给定一个可包含重复数字的序列 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]]
提示:
1 <= nums.length <= 8
-10 <= nums[i] <= 10
实现代码
解题细节在代码注释中,该题重点在剪枝条件上
和题目编号46. 全排列1 相似,细节不懂的可以去看该题的讲解
https://blog.csdn.net/qq_37079157/article/details/109495773
// 剪枝条件:i > 0 是为了保证 nums[i - 1] 有意义
//nums[i] == nums[i-1] 判断是不是重复的点,这也是排序是剪枝的前提的原因
// 写 !used[i - 1] 是因为 nums[i - 1] 在深度优先遍历的过程中刚刚被撤销选择,也就是重置为false。
/**
*
* @param nums
* @attr res 存储所有的结果。
* @attr path 存储一次结果。
* @attr used 控制状态。
* @attr depth 目前递归深度。
* @return
*/
public List<List<Integer>> permuteUnique(int[] nums) {
int len = nums.length;
List<List<Integer>> res = new ArrayList<>();
Deque<Integer> path = new ArrayDeque<>();
boolean[] used = new boolean[len];
Arrays.sort(nums); //排序是剪枝的基础前提。
giveBack(res,path,used,nums,0,len);
return res;
}
public void giveBack(List<List<Integer>> res,Deque<Integer> path,boolean[] used,int[] nums,int depth,int len){
if (depth == len){
res.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < len; i++) {
if (used[i]){
continue;
}
// 剪枝条件:i > 0 是为了保证 nums[i - 1] 有意义
//nums[i] == nums[i-1] 判断是不是重复的点,这也是排序是剪枝的前提的原因
// 写 !used[i - 1] 是因为 nums[i - 1] 在深度优先遍历的过程中刚刚被撤销选择,也就是重置为false。
if (i>0&&nums[i] == nums[i-1] && !used[i-1]){
continue;
}
path.addLast(nums[i]);
used[i] = true;
giveBack(res,path,used,nums,depth+1,len);
path.removeLast();
used[i] = false;
}
}