

解法一:用一个boolean数组记录用过的数字
class Solution {
LinkedList<Integer> path = new LinkedList<>();
List<List<Integer>> res = new ArrayList<>();
int size;
boolean[] visited;
public List<List<Integer>> permute(int[] nums) {
size = nums.length;
visited = new boolean[size];
dfs(nums);
return res;
}
public void dfs(int[] nums) {
if (path.size() == size) {
res.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; i++) {
if (visited[i]) {
continue;
}
path.add(nums[i]);
visited[i] = true;
dfs(nums);
path.removeLast();
visited[i] = false;
}
}
}
解法二:往下曾拷贝新的候选list
class Solution {
List<Integer> path = new ArrayList<>();
List<List<Integer>> res = new ArrayList<>();
int size;
public List<List<Integer>> permute(int[] nums) {
size = nums.length;
List<Integer> candidates = new ArrayList<>();
for (int x : nums) {
candidates.add(x);
}
dfs(candidates);
return res;
}
public void dfs(List<Integer> candidates) {
if (path.size() == size) {
res.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < candidates.size(); i++) {
path.add(candidates.get(i));
List<Integer> newList = new ArrayList<>(candidates);
newList.remove(i);
dfs(newList);
path.remove(path.size() - 1);
}
}
}