题目:
解析:
代码:
//用于返回最后的结果
private List<List<Integer>> ret;
//记录决策树元素的路径
private List<Integer> path;
//标记决策树元素,元素没有被使用为默认false
private boolean[] check;
public List<List<Integer>> permute(int[] nums) {
ret = new ArrayList<>();
path = new ArrayList<>();
check = new boolean[nums.length];
dfs(nums);
return ret;
}
private void dfs(int[] nums){
//递归出口
if(path.size() == nums.length) {
ret.add(new ArrayList<>(path));
return;
}
for(int i = 0; i < nums.length; i++){
//决策树的元素没有被选,就加入path
if(check[i] == false){
path.add(nums[i]);//记录路径
check[i] = true;//被使用过就设置为false
dfs(nums);
//回溯:把path最后一个元素删除
path.remove(path.size()-1);
//剪枝:把元素标志位还原
check[i] = false;
}
}
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有