回溯法/深度优先搜索
回溯法按深度优先搜索 搜索问题的解空间树。首先从根节点出发搜索解空间树,当算法搜索至解空间树的某一节点时,先利用剪枝函数 判断该节点是否可行。如果不可行,则跳过对该节点为根的子树搜索,逐层向其祖先节点回溯;否则,进入该子树,继续按深度优先策略搜索。
示例:
leetcode第22题: 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[ "((()))", "(()())", "(())()", "()(())", "()()()"]
题解:
class Solution {
List<String> result = new ArrayList<>();
public List<String> generateParenthesis(int n) {
dps("",0,0,n);
return result;
}
/**
* 回溯法(深度优先搜素)
* @param str 当前的String
* @param left 当前String已经使用的左括号个数
* @param right 当前String已经使用的右括号个数
* @param n 总共需要几对括号
*/
public void dps(String str, int left, int right, int n) {
if (left == n && right == n) {
result.add(str);
return;
}
if (left == n + 1 || right == n + 1)
return;
// 若使用的左括号数量小于使用了的右括号数,则说明str已经无效
if (left < right)
return;
dps(str + "(", left + 1, right, n);
dps(str + ")", left, right + 1, n);
}
}
class Solution {
List<String> result = new ArrayList<>();
public List<String> generateParenthesis(int n) {
// dfs("", 0, 0, n);
dfsWithStack(n);
return result;
}
// dfs的栈实现
private class Node {
public String str;
public int left;
public int right;
public Node(String str) {
this.str = str;
}
public Node(String str, int left, int right) {
this.str = str;
this.left = left;
this.right = right;
}
}
/**
* dfs的栈实现
*/
public void dfsWithStack(int n)
{
Deque<Node> deque = new LinkedList<>();
deque.addFirst(new Node("",0,0));
while(!deque.isEmpty()){
Node node = deque.removeFirst();
if(node.left == n && node.right == n)
result.add(node.str);
else if(node.left<node.right)
continue;
else{
if(node.left != n)
deque.addFirst(new Node(node.str+"(",node.left+1,node.right));
if(node.right != n)
deque.addFirst(new Node(node.str+")",node.left,node.right+1));
}
}
}
}
总结:
如果一时不知道如何下手写一个深度优先搜索的算法代码,可以用如上的算法模板。如上分出了1)dfs的递归实现与2)dfs的非递归实现/对战实现。将堆栈实现中的栈改为队列,dfs就会变成wfs(广度优先搜索)。