1、回溯算法
- 1.1 概念:搜索尝试过程中寻找问题的解,当发现已不满足求解条件时,就“回溯”返回,尝试别的路径。
- 1.2 要点:在回溯点的时候,做了什么需要还原
- 1.3 一般步骤:
针对给出的问题,确定问题的解空间(简单来说就是暴力法找到所有解)
确定结点的扩展搜索规则
以深度优先的方式搜索解空间,并在搜索过程中,使用剪枝的思想减少算法复杂度
例题1:leetcode 46 全排列
public List<List<Integer>> permute(int[] nums) {
int len = nums.length;
List<List<Integer>> res = new ArrayList();
if(len == 0){
return res;
}
boolean[] used = new boolean[len];
Deque<Integer> path = new LinkedList();
dfs(nums, len, 0, used, path, res);
return res;
}
private void dfs(int[] nums,int len, int depth, boolean[] used,Deque<Integer> path, List<List<Integer>> res){
if(depth == len){
res.add(new ArrayList(path));
return;
}
for(int i = 0; i < len; i++){
if(used[i]){
continue;
}
path.addLast(nums[i]);
used[i] = true;
dfs(nums,len,depth+1,path,res);
path.removeLast();
used[i] = false;
}
}
例题2:leetcode 47 全排列Ⅱ
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
int len = nums.length;
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
if(len == 0