全排列
回溯经典题目
思路:
典型的回溯题目。
重点是 for
loop 不能从 start
开始,因为要遍历全部数组,所以要从 0
开始。
也正是因为需要遍历全部数组, used
数组要声明为 全局 的,这样可以记录是否遍历过。
class Solution {
LinkedList<Integer> path = new LinkedList<>();
List<List<Integer>> res = new ArrayList<>();
boolean[] used = new boolean[21];
public List<List<Integer>> permute(int[] nums) {
backtrack(nums);
return res;
}
private void backtrack(int[] nums) {
if (path.size() == nums.length) {
res.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; i++) {
if (used[i]) continue;
used[i] = true;
path.add(nums[i]);
backtrack(nums);
path.removeLast();
used[i] = false;
}
}
}