排列的回溯问题不能使用start,⾸先排列是有序的,也就是说[1,2] 和[2,1] 是两个集合,可以看出元素1在[1,2]中已经使⽤过了,但是在[2,1]中还要在使⽤⼀次1,所以不能用start。
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> permute(int[] nums) {
if (nums.length == 0) return result;
dfs(nums, path);
return result;
}
public void dfs(int[] nums, LinkedList<Integer> path) {
if (path.size() == nums.length) {
result.add(new ArrayList<>(path));
}
for (int i =0; i < nums.length; i++) {
// 如果path中已有,则跳过
if (path.contains(nums[i])) {
continue;
}
path.add(nums[i]);
dfs(nums, path);
path.removeLast();
}
}
}
本文介绍了一种使用回溯法求解排列问题的方法,通过递归深度优先搜索实现,避免了元素重复使用的问题。文章提供了一个具体的Java实现案例。
429

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



