LeetCode.46 全排列(Medium)
回溯算法的本质就是穷举,因而决定了他的复杂度是O(N!)。
回溯算法的核心主要是四步:
1. 在for循环之前做“判断”
2. 在for循环里面做“递归”
3. 在递归之前做“选择”
4. 在递归之后做“撤销”
class Solution {
private List<List<Integer>> res;
public List<List<Integer>> permute(int[] nums) {
res = new LinkedList<>();
permute_helper(nums, new LinkedList<Integer>());
return res;
}
private void permute_helper(int[]nums, LinkedList<Integer> path) {
// 1.在for循环前判断(终止条件)
if (nums.length == path.size()) {
res.add(new LinkedList<Integer>(path));
return;
}
for (int i = 0; i < nums.length; ++i) {
if (path.contains(nums[i])) continue;
// 2.在递归前做选择
path.add(nums[i]);
// 3.在for循环里递归
permute_helper(nums, path);
// 4.在递归后做撤销
path.removeLast();
}
}
}