递归
def recursion(level, param1, param2,...):
# recursion terminator
if level > MAX_LEVEL:
return
# process login in current level
process_data(level, data,...)
# drill down
self.recursion(level + 1, p1, ...)
# reverse the current level status if needed
reverse_state(level)
广度优先搜索
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(next_node, visited)
深度优先搜索
def bfs(graph, start, end):
queue = []
queue.append([start])
visited.add(start)
while queue:
node = queue.pop()
visited.add(node)
process(node)
nodes = generate_related_nodes(node)
queue.push(nodes)
# other processing work
二分
left, right = 0, len(array) - 1
while left < right:
mid = left + (right - left) /2
if array[mid] == target:
# find the target
break or return result
elif array[mid] < target:
left = mid + 1
else:
right = 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]