https://leetcode.com/problems/jump-game-ii/ Solution (Dynamic Programming) class Solution: def jump(self, nums: List[int]) -> int: DP = [0] + [float("inf")]* (len(nums) - 1) for i in range(len(nums ...
分治法 Divide and Conquer 總是能夠將「問題 X 」拆分為「問題 A 」和「問題 B 」 滿足「問題 A 」+「問題 B 」=「問題 X 」 且能確定「問題 X 」的解只存在於「問題 A 」或「問題 B 」兩者其中之一 如果「問題 X 」的 brute force 解法之 time complexity 為 O(n) 則使用 binary method 的時間複雜度將減少為 O( ...
https://leetcode.com/problems/course-schedule-ii/ Explanation 使用 in-degree 關鍵在於 優先提取 in-degree 為 0 的 vertex(即該 vertex 已無任何前導 vertex) vertex被提取時,調整其子 vertex 的 in-degree 當 graph 中有 loop 當 graph 中有 loop ...
list 常用操作 Operation Syntax ATC Append an item x to the last lst.append(x) O(1) Remove and return the last (most left) item in the list lst.pop() O(1) Remove and return the ith item in the list lst.pop ...
https://leetcode.com/problems/longest-palindromic-substring/ Solution Dynamic Programming \begin{align*} & \text{定義 } P(i, j) \text{ 為:} \\ & P(i, j)= \begin{cases} True & \text{, if the s ...
https://leetcode.com/problems/numbers-at-most-n-given-digit-set/ Solution class Solution: def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int: n_str = str(n) l = len(n_str) dp = [0] * ...
https://leetcode.com/problems/reorder-list/ Key point 使用一快一慢的pointer來找到length和middle node Solution class Solution: def reorderList(self, head: Optional[ListNode]) -> None: """ Do not return anythin ...
概覽 Syntax Description Average Time Complexity Space Complexity list_b = sorted(list_a) 回傳排序好的新list O(n * log(n)); n = len(list_a) O(n) list_a.sort() 將list_a排序 O(n * log(n)) O(n) 常用auguments key 排序時以ke ...
https://leetcode.com/problems/maximum-subarray/ Solution \begin{align} &\text{max_ending_here } := \mathop{\max}_{i \in [0, j]}\quad{\mathop{\sum}_{k=i}^j{nums[k]}} \\ &\text{max_so_far } := \ ...
動態規劃在尋找有很多重疊子問題的情況的最佳解時有效。 動態規劃儲存遞迴時計算子問題的結果, 因而不會在解決同樣的問題時花費時間。 適用條件 最佳子結構 Optimal Substructure 如果問題的最佳解所包含的子問題的解也是最佳的,我們就稱該問題具有最佳子結構性質(即滿足最佳化原理)。最佳子結構性質為動態規劃演算法解決問題提供了重要線索。 無後效性 Without Aftereffect ...