使用場景:常見於各類組合,樹遍歷,前序遍歷、中序遍歷、後續遍歷html
private void dfs(int[] arr, int target,int begin, Deque<Integer> path, Set<List<Integer>> res) { if ( path.size()== target) { res.add(new ArrayList<>(path)); return; }else if(begin>arr.length){ return; } for (int i = begin; i < arr.length; i++) { path.add(arr[i]); dfs(arr,target,i+1,path,res); path.removeLast(); } }
常見於樹遍歷,樹層級,節點next指針等場景java
public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> levelOrder = new LinkedList<List<Integer>>(); if (root == null) { return levelOrder; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); while (!queue.isEmpty()) { List<Integer> level = new ArrayList<Integer>(); int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode node = queue.poll(); level.add(node.val); TreeNode left = node.left, right = node.right; if (left != null) { queue.offer(left); } if (right != null) { queue.offer(right); } } levelOrder.add(0, level); } return levelOrder; }
常見於求最長連續字符、累計值最大等場景,node
迴文字符串指針
參見快慢指針code