// 常见模型:找出每个数左边离它最近的比它大/小的数 int tt = 0; for (int i = 1; i <= n; i ++ ) { while (tt && check(stk[tt], i)) tt -- ; stk[ ++ tt] = i; }
深搜模版
1 2 3 4 5 6 7 8 9 10
boolean DFS(Node cur, Node target, Set<Node> visited){ returntrueif cur is target; for (next : each neighbor of cur) { if (next is not in visited) { add next to visted; returntrueifDFS(next, target, visited) == true; } } returnfalse; }
intBFS(Node root, Node target){ Queue<Node> queue; int step = 0; // number of steps neeeded from root to current node // 初始化 add root to queue; // BFS while (queue is not empty) { step = step + 1; // iterate the nodes which are already in the queue int size = queue.size(); for (int i = 0; i < size; ++i) { Node cur = the first node in queue; return step if cur is target; for (Node next : the neighbors of cur) { add next to queue; } remove the first node from queue; } } return-1; // there is no path from root to target }