BFS好题选编
301. Remove Invalid Parentheses
经测试,BFS
比backtracking
快得多!
注意到题目中要求最少删除,这样的描述正是广度优先搜索算法应用的场景,并且题目也要求我们输出所有的结果。我们在进行广度优先搜索时每一轮删除字符串中的 1 个括号,直到出现合法匹配的字符串为止,此时进行轮转的次数即为最少需要删除括号的个数。
我们进行广度优先搜索时,每次保存上一轮搜索的结果,然后对上一轮已经保存的结果中的每一个字符串尝试所有可能的删除一个括号的方法,然后将保存的结果进行下一轮搜索。在保存结果时,我们可以利用哈希表对上一轮生成的结果去重,从而提高效率。
1 | class Solution { |
133. Clone Graph
1 | Map<Node,Node> map; |
1 | Node[] clone; |
269. Alien Dictionary
拓扑排序,用dfs需要三要素+后序遍历逆序,用bfs结果无需逆序,也需三要素:
- 入度数组
- 出队计数器count
- 当前入度为0的queue
1 | public String alienOrder(String[] words) { |
优化:
1 | public String alienOrder(String[] words) { |
100. Same Tree
DFS:
1 | public boolean isSameTree(TreeNode p, TreeNode q) { |
BFS:
1 | public boolean isSameTree(TreeNode p, TreeNode q) { |
102. Binary Tree Level Order Traversal
1 | public List<List<Integer>> levelOrder(TreeNode root) { |
103. Binary Tree Zigzag Level Order Traversal
1 | public List<List<Integer>> zigzagLevelOrder(TreeNode root) { |
104. Maximum Depth of Binary Tree
DFS:
1 | public int maxDepth(TreeNode root) { |
BFS:
1 | public int maxDepth(TreeNode root) { |
310. Minimum Height Trees
BFS (Time Limit Exceeded)
1 | public class LeetCode310 { |
Topological sort
- find out the centroids of the circle, i.e. nodes that is close to all the peripheral nodes (leaf nodes)
- For the tree-alike graph, the number of centroids is no more than 2.
- proved by contradiction
- Given the above intuition, the problem is now reduced down to looking for all the centroid nodes in a tree-alike graph, which in addition are no more than two.
- algorithm: trim out the leaf nodes, layer by layer!!
1 | class Solution { |
1 | public List<Integer> findMinHeightTrees(int n, int[][] edges) { |
111. Minimum Depth of Binary Tree
DFS:
1 | public int minDepth(TreeNode root) { |
BFS:
1 | public int minDepth(TreeNode root) { |
112. Path Sum
DFS:
1 | public boolean hasPathSum(TreeNode root, int targetSum) { |
BFS:
1 | public boolean hasPathSum(TreeNode root, int targetSum) { |
116. Populating Next Right Pointers in Each Node
O(N) time, O(N) space:
1 | public Node connect(Node root) { |
O(N) time, O(1) space:
1 | class Solution { |
1 | public Node connect(Node root) { |
127. Word Ladder
1 | public int ladderLength(String beginWord, String endWord, List<String> wordList) { |
126. Word Ladder II
easy to count, but how to store the shortest transformation sequeneces?
226. Invert Binary Tree
DFS:
1 | public TreeNode invertTree(TreeNode root) { |
BFS:
1 | public TreeNode invertTree(TreeNode root) { |
279. Perfect Squares
1 | public int numSquares(int n) { |
286. Walls and Gates
DFS: run time exceeded
1 | public class LeetCode286 { |
BFS: O(mn) time and space complexity
1 | private static final int EMPTY = Integer.MAX_VALUE; |
302. Smallest Rectangle Enclosing Black Pixels
Approach 1: Naive Linear Search
1 | public int minArea(char[][] image, int x, int y) { |
Approach 2: BFS/DFS
1 | public int minArea(char[][] image, int x, int y) { |
317. Shortest Distance from All Buildings
level-ordered BFS
1 | public class LeetCode317 { |
339. Nested List Weight Sum
DFS:
1 | public int depthSum(List<NestedInteger> nestedList) { |
BFS:
1 | public int depthSum(List<NestedInteger> nestedList) { |
365. Water and Jug Problem
At any state (a,b) of the jugs we can do 6 things.
- Pour contents of jug1 to jug2. (note that jug1 may still have some water left after pouring water to jug2)
- Pour contents of jug2 to jug1. (note that jug2 may still have some water left after pouring water to jug1)
- Empty jug1 completely.
- Empty jug2 completely.
- Fill jug1 completely (to its maximum limit)
- Fill jug2 completely (to its maximum limit)
We are going to keep a note of the already visited states (a,b) of the jugs in a HashSet of string with key being: “a,b” (the capacities of the jugs separated by a comma. This helps us to avoid redundant calculations).
We are going to start with a queue containing only the state (0,0) (both jugs empty) initially. Apply the above 6 operations on that and add those states to the queue if they weren’t already visited. Then simply keep checking whether in any of the states we get the summation of the capacities == z.
If we don’t find any such state. return false.
BFS: Time Limit Exceeded
1 | class State{ |
Math
ax + by = k*gcd(a,b)
1 | public boolean canMeasureWater(int x, int y, int z) { |
404. Sum of Left Leaves
DFS:
1 | public int sumOfLeftLeaves(TreeNode root) { |
BFS:
1 | public int sumOfLeftLeaves(TreeNode root) { |
407. Trapping Rain Water II
1 | public class Cell { |
433. Minimum Genetic Mutation
1 | public int minMutation(String startGene, String endGene, String[] bank) { |
542. 01 Matrix
1 | public int[][] updateMatrix(int[][] mat) { |
623. Add One Row to Tree
1 | if(depth==1){ |
662. Maximum Width of Binary Tree
1 | public int widthOfBinaryTree(TreeNode root) { |