这是一道深度优先遍历的题目。或者说搜索回溯,有状态标记,有中止条件判定。
public class Solution {
public List<List<Integer>> permute(int[] nums) {
int len = nums.length;
List<List<Integer>> res = new LinkedList<>();
if (len == 0) {
return res;
}
boolean[] mark = new boolean[len];
int depth = 0;
LinkedList<Integer> path = new LinkedList<>();
dfs(nums, mark, depth, res, len, path);
return res;
}
private void dfs(int[] nums, boolean[] mark, int depth, List<List<Integer>> res, int len, LinkedList<Integer> path) {
if (depth == len) {
res.add(new LinkedList<>(path));
return;
}
for (int i = 0; i < len; i++) {
if (mark[i]) {
continue;
}
path.add(nums[i]);
mark[i] = true;
depth++;
dfs(nums, mark, depth, res, len, path);
depth--;
mark[i] = false;
path.removeLast();
}
}
}