文章目录

  • 1.回溯算法
  • 2.回溯算法模板
  • 3.回溯实例(77、216、17、39、40、131、93、78、90、491、46、47)
  • 4.总结

1.回溯算法

回溯算法的本质就是穷举,最多再加上剪枝,剪掉一部分不必要的。
关于排列组合的区别,组合无序,排列有序
回溯算法解决问题都可以抽象为树形结构(N叉树),树的宽度代表集合的大小,树的深度代表递归的深度,树的高度是有限的,也就是递归是有终止条件的。

2.回溯算法模板

void backtracking(参数) :if (终止条件) :存放结果returnfor (选择:本层集合中元素(树中节点孩子的数量就是集合的大小)):处理节点backtracking(路径,选择列表) # 递归回溯,撤销处理结果

3.回溯实例(77、216、17、39、40、131、93、78、90、491、46、47)

77. 组合 - 力扣(LeetCode) (leetcode-cn.com)



剪枝需要在for里面做处理

class Solution:def combine(self, n: int, k: int) -> List[List[int]]:def backtracking(i):if not len(path)-k: return res.append(path[:])for j in range(i,n-(k-len(path)-1)):#if j>n-(k-len(path)):break  #剪枝path.append(j+1)backtracking(j+1)path.pop()      res=[]  #存放符合条件结果的集合path=[]  #用来存放符合条件结果backtracking(0)return res

216. 组合总和 III - 力扣(LeetCode) (leetcode-cn.com)

class Solution:def combinationSum3(self, k: int, n: int) -> List[List[int]]:def backtracking(sumer,i):if not sumer and not len(path)-k:return res.append(path[:])for j in range(i,9):if sumer-j-1<0:break  #剪枝path.append(j+1)backtracking(sumer-j-1,j+1)path.pop()path =[]res = []backtracking(n,0)return res

17. 电话号码的字母组合 - 力扣(LeetCode) (leetcode-cn.com)

class Solution:def letterCombinations(self, digits: str) -> List[str]:def backtracking(digits):if not digits:return res.append(''.join(path))       #如果为空开始收集数据index = int(digits[0])-2for i in nums[index]:path.append(i)backtracking(digits[1:])path.pop()nums=['abc','def','ghi','jkl','mno','pqrs','tuv','wxyz']path =[]res = []backtracking(digits)return res if digits else []

39. 组合总和 - 力扣(LeetCode) (leetcode-cn.com)

class Solution:def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:def backtacking(target,index):if not target: return res.append(path[:])for i in range(index,len(candidates)):if target-candidates[i]<0:return #剪枝path.append(candidates[i])backtacking(target-candidates[i],i)path.pop()res, path = [], []candidates.sort()backtacking(target,0)return res

40. 组合总和 II - 力扣(LeetCode) (leetcode-cn.com)

class Solution:def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:def backtacking(target,index):if not target: return res.append(path[:])for i in range(index,len(candidates)):if target-candidates[i]<0: break                           #剪枝if i>index and not candidates[i]-candidates[i-1]:continue   #剪掉重复项path.append(candidates[i])backtacking(target-candidates[i],i+1)path.pop()res, path = [], []candidates.sort() #排序方便后面的回溯backtacking(target,0)return res

131. 分割回文串 - 力扣(LeetCode) (leetcode-cn.com)

class Solution:def partition(self, s: str) -> List[List[str]]:def backtracking(index):if not index-len(s): return res.append(path[:])for i in range(index,len(s)):selectS= s[index:i+1]if selectS!=selectS[::-1]:continuepath.append(selectS)backtracking(i+1)path.pop()res, path = [], []backtracking(0)return res

93. 复原 IP 地址 - 力扣(LeetCode) (leetcode-cn.com)

class Solution:def restoreIpAddresses(self, s: str) -> List[str]:def backtracking(index,count):if not index- len(s) and not count:return res.append('.'.join(path[:]))for i in range(index,len(s)):temp = s[index:i+1]if count<0: break                                            #大于4个的 跳出if int(temp)>255 or len(temp)>1 and not int(temp[0]):break  #判断是否为有效ippath.append(s[index:i+1])backtracking(i+1,count-1)path.pop()res, path = [], []backtracking(0,4)return res

78. 子集 - 力扣(LeetCode) (leetcode-cn.com)
不同于前面的是每次结果,它都会收集

class Solution:def subsets(self, nums: List[int]) -> List[List[int]]:def backtracking(nums):res.append(path[:])if  not len(nums): return for i in range(len(nums)):path.append(nums[i])backtracking(nums[i+1:])path.pop()res, path = [], []backtracking(nums)return res

90. 子集 II - 力扣(LeetCode) (leetcode-cn.com)

class Solution:def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:def backtracking(nums):res.append(path[:])if not nums:returnfor i in range(len(nums)):if i>0 and not nums[i]-nums[i-1]:continue#剪枝path.append(nums[i])backtracking(nums[i+1:])path.pop()res, path = [], []nums.sort()backtracking(nums)return res

491. 递增子序列 - 力扣(LeetCode) (leetcode-cn.com)

class Solution:def findSubsequences(self, nums: List[int]) -> List[List[int]]:def backtracking(nums):if len(path)>1:res.append(path[:])  #只取内元素个数大于等于2if not nums:return 0# 深度遍历中每一层都会有一个全新的usage_list用于记录本层元素是否重复使用usage_list = set()for i in range(len(nums)):#递增的保证if path and nums[i]<path[-1]:continue  #判断是为递增if nums[i] in usage_list:continue  #去除重复项usage_list.add(nums[i])path.append(nums[i])backtracking(nums[i+1:])path.pop()res, path = [], []backtracking(nums)return res

46. 全排列 - 力扣(LeetCode) (leetcode-cn.com)

class Solution:def permute(self, nums: List[int]) -> List[List[int]]:def backstacking(nums):if not nums:return res.append(path[:]) for i in range(len(nums)):path.append(nums[i])backstacking(nums[:i]+nums[i+1:])path.pop()res, path = [], []backstacking(nums)return res

47. 全排列 II - 力扣(LeetCode) (leetcode-cn.com)

class Solution:def permuteUnique(self, nums: List[int]) -> List[List[int]]:def backtracking(nums):if not nums:return res.append(path[:])dedup= set()  #去掉某一层一样的for i in range(len(nums)):if nums[i] in dedup:continuededup.add(nums[i])path.append(nums[i])backtracking(nums[:i]+nums[i+1:])path.pop()res, path= [], []backtracking(nums)return res

4.总结

还留下三道困难题,明天再看了,如果明天看完比较早,那就往下看贪心算法,希望一切顺利!

力扣刷题-python-回溯算法-1(回溯算法模板、题型)相关推荐

  1. 教你创建电脑、手机同步的markdown云笔记--力扣刷题力荐!

    开篇先致歉 其他不谈,开篇必须先给各位读者道个歉,年后工作上比较忙,加上最近闲暇的时间都用来在力扣上刷算法题了,导致公众号断更有些严重啊.再加上年后将健身减重提上了日程,时间上就更显的捉襟见肘了. 不 ...

  2. 力扣刷题pdf(java版本,内含暗黑版和光明版),都在这里了

    BAT大佬力扣刷题pdf,都在这里了! ​相信很多小伙伴刷题的时候面对力扣上近两千道题目,感觉无从下手! 我找了很久,今天终于让找到了Java版leetcode算法题解笔记,强烈建议先按照本篇介绍pd ...

  3. 力扣刷题——双数之和

    很多人去力扣刷题都是数组的第一题,也就是双数之和,相信这也是很多人劝退题目,甚至对自己学过的知识产生了怀疑,这真的是我学完C语言,Java,Python或C++之后能做出来的题目吗?直接劝退了很多人, ...

  4. 力扣刷题记录--哈希表相关题目

    当遇到需要快速判断一个元素是否出现在集合里面的时候,可以考虑哈希法,牺牲一定的空间换取查找的时间. java常用的哈希表有HashMap.HashSet以及用数组去模拟哈希,这几种方法各有优劣. 数组 ...

  5. 力扣刷题笔记--168. Excel表列名称

    题目描述: 简单题 给你一个整数 columnNumber ,返回它在 Excel 表中相对应的列名称. 例如: A -> 1 B -> 2 C -> 3 ... Z -> 2 ...

  6. 《剑指Offer》力扣刷题笔记(03-10)

    <剑指Offer>力扣刷题笔记(03-10) 最近确实有点闲,想在进组搬砖之前找点有意义的事干,于是,就开始刷<剑指Offer>.<程序员面试金典>等书上的题目,也 ...

  7. 力扣刷题之二叉树的层序遍历

                                                      Welcome to you, 每日一刷系列 二叉树的层序遍历 二叉树的层序遍历II 二叉树的右视图 ...

  8. 『力扣刷题』5275_找出井字棋的获胜者 解题代码

    LeetCode-cn 力扣刷题 LeetCode-cn力扣刷题目录 165周赛 5275_找出井字棋的获胜者 * 5275. 找出井字棋的获胜者 显示英文描述* 用户通过次数0* 用户尝试次数0* ...

  9. 『力扣刷题』5276_不浪费原料的汉堡制作方案 解题代码

    LeetCode-cn 力扣刷题 LeetCode-cn力扣刷题目录 165周赛 5276_不浪费原料的汉堡制作方案 * 5276. 不浪费原料的汉堡制作方案 显示英文描述* 用户通过次数212* 用 ...

  10. 『力扣刷题』5238_找出给定方程的正整数解 解题代码

    html: embed_local_images: true embed_svg: true offline: true toc: undefined print_background: false ...

最新文章

  1. FPGA逻辑设计回顾(1)新手易犯的逻辑综合错误之always块
  2. 如何将结婚当作项目来管理
  3. NOI 2015 滞后赛解题报告
  4. 工业以太网交换机故障的排障步骤
  5. VMware-构建下一代的服务器虚拟化平台
  6. 邮政储蓄计算机笔试题,邮储总行计算机类笔试题
  7. 管家婆服装.NET II TOP V6.5-VIP卡使用注意事项(一)
  8. 大一计算机期末考试操作题word,Word大一计算机考试操作题
  9. 部落战魂找不到服务器,部落战魂官方版
  10. android手机电话铃声设置,安卓怎么设置铃声 安卓手机铃声设置教程
  11. 关于统计学的一些思考(一)
  12. spring之----事务
  13. CSS实现有“边框”的下三角
  14. python数据分析常见错误_Python数据分析常用语句(一)
  15. ME02 认知之2017罗胖跨年演讲
  16. Python学习——import用法
  17. EveryThing下载链接
  18. 阿里巴巴ICBU技术部招人啦
  19. 天津理工大学计算机网络实验报告二,天津理工大学计算机网络实验报告一(中加).docx...
  20. doT js模板入门 3

热门文章

  1. 计算机硬盘越大运行速度越大吗,电脑的内存越大越好吗?如果只加大内存,电脑反而会被拖慢!...
  2. plt.imshow()中cmap参数控制颜色展示
  3. lol韩服游戏内设置_韩服LOL进去了还不能玩?教你如何玩韩服!
  4. 思科大学计算机第一章测试题及答案,集美大学思科上机练习1
  5. vba中如何使用函数counta
  6. 你只管打开这个网站,剩下的交给「卧槽」
  7. 杭州电子科技大学acm---2010
  8. 2022安徽安全员B考试单选题库预测分享
  9. 告别 Google 网站站长,迎接 Google 搜索中心
  10. 爬微医挂号网并把数据导入oracle数据库