這幾種演算法不僅要理解,更要能背下來虛擬碼,讓這些演算法的回想變成O(1)的時間複雜度。
- Recursion 遞迴
def recursion(level, param1, param2, ...):
# recursion terminator
if level > MAX_LEVEL:
print_result
return
# process logic in current level
process_data(level, data...)
# drill down
self.recursion(level+1, p1, p2, ...)
# reverse the current level status if needed
reverse_state(level)
DFS(遞迴寫法)
visited = set() def dfs(node, visited) visited.add(node) # process current node here. ... for next_node in node.children(): if not next_node in visited: dfs(node, visited)
–DFS(非遞迴寫法)
def dfs(graph, start, end): stack = [] visited = set() stack.append(start) while stack: node = stack.pop() visited.add(node) # process current node here ... for next_node in node.children(): if not next_node in visited: stack.append(next_node)
BFS
def bfs(graph, start, end): queue = Queue() visited = set() queue.enqueue(start) while queue: node = queue.dequeue() visited.add(node) # process current node here ... for next_node in node.children(): if not next_node in visited: queue.enqueue(next_node)
binary search
l, r = 0, len(array) - 1 while l <= r: mid = l + (r - l) // 2 if array[mid] == target: # find the target! break or return result elif array[mid] < target: l = mid + 1 else: r = mid - 1
二分查詢還有幾種變形,想法類似。第一個大於、大於等於、小於、小於等於的數
DP
// 狀態定義 dp = new int[m+1][n+1] // 初始狀態 dp[0][0] = x; dp[0][1] = y; ... // DP狀態推導 for i = 0; i <= n; ++i { for j = 0; j <= m; ++j { ... dp[i][j] = min{dp[i-1][j], dp[i][j-1], etc.} } } return dp[m][n] // 最優解
本作品採用《CC 協議》,轉載必須註明作者和本文連結