常见算法代码模板

你离开我真会死。 提交于 2019-11-30 22:39:11

递归

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]
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!