题目描述
给定一个不含重复数字的数组nums返回其所有可能的全排列 。你可以按任意顺序返回答案。
示例

题解
回溯法,构建树结构,注意剪枝。
代码
class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> permute(int[] nums) {
if (nums.length == 0) {
return res;
}
deep(nums, 0, new ArrayList<Integer>());
return res;
}
public void deep(int[] nums, int loop, List<Integer> tmp) {
int len = nums.length;
if (loop == len) {
res.add(new ArrayList<>(tmp));
return;
}
for (int i = 0; i < len; i++) {
// 如当前元素已在结果中出现,则剪枝
if (tmp.contains(nums[i])) {
continue;
}
tmp.add(nums[i]);
deep(nums, loop + 1, tmp);
tmp.remove(tmp.size() - 1);
}
}
}
性能

注意点
当不确定循环次数时,第一反应就要是回溯。注意判断剪枝条件。

该博客探讨了如何使用回溯法解决数组全排列的问题。通过构建树结构并利用剪枝技巧,实现了在不重复的情况下生成所有可能的排列组合。文章提供了详细的代码实现,并强调了在循环次数不确定时优先考虑回溯法的重要性。
315

被折叠的 条评论
为什么被折叠?



