23. Merge k Sorted Lists
題目網址:https://leetcode.cn/problems/merge-k-sorted-lists/
題意:給一 linked list array lists, 每個 linked list 都已按照升序排列。
將所有 linked list 合併成一個升序的 linked list, 並返回合併後的 linked list。
Solution 1:
想法:利用 Heap 來紀錄所有 linked list 當前的 node.val, 每次取 heap 中最小的 node cur, 並加到新的 linked list 中。若 cur->next 不為 null, 則將其加到 heap 中(能這樣做是因為每個 linked list 皆已排序過)
class Solution {public: ListNode* mergeKLists(vector<ListNode*>& lists) { const auto cmp = [](auto& n1, auto& n2){ ...
25. Reverse Nodes in k-Group
題目網址:https://leetcode.cn/problems/reverse-nodes-in-k-group/
題意:給一 linked list 的 head, 每 k 個 node 一組進行 reverse, 返回修改後的 linked list。
k 為一正整數, 其中 k ≤ linkedList.size()。如果 node 數不為 k 的倍數, 則讓剩餘的 node 保持原先的順序。
必須實際進行 swap node, 不能只是單純改變 node.val。
進階:設計 $O(1)$ space 的演算法。
Solution:
想法:分成以下步驟
先用 groupPre 指向 group 開頭的前一個 node
取得該 group 的第 k 個 node kth, 也就是 group end
reverse 從 group head ~ group end 的 node
prev 起始設為 kth->next, 因為 reverse 後 group end 必須連接到剩下的 node
reverse 完後, 首先記住 reverse 後的 grou ...
124. Binary Tree Maximum Path Sum
題目網址:https://leetcode.cn/problems/binary-tree-maximum-path-sum/
題意:給一 BT 的 root, 返回其最大的 path sum。
path 定義:為一條從 tree 中任意 node 出發, 最後抵達任意 node 的 sequence。同一個 node 在一條 path 中至多出現一次。該 path 至少包含一個 node, 且不一定經過 root。
Solution:
想法:利用 DFS, 類似 543. Diameter of Binary Tree, dfs(node) 返回以 node 為 root 之 subtree 中 path sum 之最大值, 只有當前 node 可以同時使用左子樹和右子樹, 也就是計算 res 時可同時用左子樹和右子樹, 但返回時只能 return 單邊路徑。由於 path 不一定要經過 root, 因此可用 global 變數 res 來記錄最大 path sum
class Solution {public: int maxPathSum(TreeNo ...
297. Serialize and Deserialize Binary Tree
題目網址:https://leetcode.cn/problems/serialize-and-deserialize-binary-tree/
題意:Serialize 是將資料結構轉換成一系列的 bit, 進而將其儲存在 file 或 buffer 中, 也可以透過網路傳輸到另一台電腦, 並重構得到原資料。
設計一個 BT 的 Serialize 和 Deserialize 功能, 讓一個 BT 可透過 Serialize 轉換成 string, 並透過 Deserialize 重構回 BT。
Solution 1:
想法:利用 DFS, 用 preorder 遍歷 BT, 並加入到 string 中, 記得 val 之間要用 ',' 隔開, 且用 '#' 代表 nullptr
idx 的 left child 必為 idx + 1
當 decodeDFS(nodes, idx) 做完後, idx 會指向下一個 preorder 位置
所以當 root->left = decodeDFS(nodes, idx) 做完後, idx 會指向 ...
212. Word Search II
題目網址:https://leetcode.cn/problems/word-search-ii/
題意:給一 m x n 的網格 board, 和一 string list words, 返回同時存在於 board 和 words 中的所有單字。
單字必須按照字母順序, 並通過相鄰的 cell 所構成, 其中相鄰是指水平相鄰 or 垂直相鄰, 且同一位置的 cell 不允許被重複使用。
其中 board[i][j] 和 words[i] 皆由小寫字母組成, 且 word 中的 string 互不相同。
Solution 1:(TLE 無法通過)
想法:利用 DFS + Backtracking, 同 79. Word Search, 每一個 words[i] 都從 (0, 0) ~ (m, n) 為起點開始搜索
class Solution {public: vector<string> findWords(vector<vector<char>>& board, vector<string>& ...