题目链接
1. 题目考点
- 回溯算法
- N叉树的遍历
- bfs
- dfs
2. 考点解析
- bfs 解法
模板
class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> permute(int[] nums) {
backTrace(nums);
return res;
}
public void backTrace(int[] nums) {
Queue<Queue<Integer>> queue = new LinkedList<>();
Queue<Integer> q = new LinkedList<>();
queue.offer(q);
while (!queue.isEmpty()) {
q = queue.poll();
if (q.size() == nums.length) res.add(new ArrayList(q));
else {
Stack<Integer> temp = new LinkedList<>(q);
for (int n : nums) {
if (!q.contains(n)) {
temp.offer(n);
queue.offer(new LinkedList(temp));
temp.remove(n);
}
}
}
}
}
}
- dfs 解法
n叉树先序遍历 + 回退操作
class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> permute(int[] nums) {
Stack<Integer> path = new Stack<>();
backTrace(nums, path);
return res;
}
public void backTrace(int[] nums, Stack<Integer> path) {
if (path.size() == nums.length) {
res.add(new ArrayList(path));
return ;
}
for (int n : nums) {
if (path.contains(n)) continue;
path.push(n);
backTrace(nums, path);
path.pop();
}
}
}