美文网首页
回溯法模板和相关题目

回溯法模板和相关题目

作者: 灰化肥发黑会挥发 | 来源:发表于2020-03-31 16:39 被阅读0次

回溯法的关键在于要画出一颗遍历树,根据树来确定遍历方法:
模板(有的题目需要添加visited数组记录遍历状态):

        def dfs(target, begin, path):
            # 结束条件
            if target == 0: 
                if path not in res:
                   # python的话一定要加: 才是复制,否则后续操作会修改
                    res.append(path[:]) 
                return
            for i in range(begin, len(candidates)):
                rediduel = target - candidates[i]
               # 减枝条件
                if rediduel < 0:
                    break
                path.append(candidates[i])
                dfs(rediduel, i+1, path)
                #最后要加pop
                path.pop()

相关题目: leetcode: 39, 40, 46, 47, 78, 90

相关文章

网友评论

      本文标题:回溯法模板和相关题目

      本文链接:https://www.haomeiwen.com/subject/dcvqrhtx.html