当前位置: 首页 > news >正文

40. 组合总和 II

题目来源:

        leetcode题目:40. 组合总和 II - 力扣(LeetCode)

解题思路:

       方法一:选或者不选当前元素,通过提前获得后续元素的和来减枝,但是还是超过时间限制。

       方法二:利用数组对所给集合进行预处理,存储 每个数字的出现次数,然后通过选不选当前元素来进行遍历。

解题代码:

#python3
#超出时间限制
class Solution:res=[]follows=[]def dfs(candidates:List[int],target:int,pos:int,chosen:List[int]):if pos>=len(candidates):return if Solution.follows[pos]<target:return newChosen=copy.deepcopy(chosen)#不选择该元素Solution.dfs(candidates,target,pos+1,newChosen)   #选择该元素newChosen.append(candidates[pos])temp=target-candidates[pos]if temp==0:Solution.res.append(newChosen)elif temp>0 and pos+1<len(candidates) and temp<=Solution.follows[pos+1]:Solution.dfs(candidates,temp,pos+1,newChosen)else:return def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:#初始化Solution.res=[]candidates.sort()Solution.follows=[0]*len(candidates)Solution.follows[len(candidates)-1]=candidates[len(candidates)-1]for i in range(len(candidates)-2,-1,-1):Solution.follows[i]=Solution.follows[i+1]+candidates[i]#计算Solution.dfs(candidates,target,0,[])#去重Solution.res.sort()reRes=[]if len(Solution.res)==0:return []else:reRes.append(Solution.res[0])for result in Solution.res:if result!=reRes[len(reRes)-1]:reRes.append(result)return reResreturn Solution.res
    #python3
    class Solution:res=[]def getAnswer(cnt:List[int],target:int,pos:int,chosen:List[int]):if target==0:Solution.res.append(chosen)elif target<0:return if pos>len(cnt):returnif pos>target:  #已超出return #选择x个for i in range(0,cnt[pos]+1):newChosen=copy.deepcopy(chosen)newTarget=target-i*posfor j in range(0,i):newChosen.append(pos)Solution.getAnswer(cnt,newTarget,pos+1,newChosen)def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:Solution.res=[]cnt=[]for i in range(0,51):cnt.append(0)for i in range(len(candidates)):cnt[candidates[i]]=cnt[candidates[i]]+1Solution.getAnswer(cnt,target,1,[])return Solution.res       

    总结:

            官方题解也是一样的思路,不过他存储用的哈希表。


    相关文章:

  1. 洛谷 P2866 [USACO06NOV] Bad Hair Day S
  2. Untiy基础学习(五)Inspector窗口中可编辑的变量
  3. Linux之用户管理
  4. SALOME源码分析: SolverLab
  5. 大模型(LLMs)RAG 版面分析——文本分块面
  6. Rust的安全卫生原则
  7. Java二维码学习
  8. Spark,Idea中编写Spark程序 2
  9. 从入门到登峰-嵌入式Tracker定位算法全景之旅 Part 4 |IMU 死算与校正:惯性导航在资源受限环境的落地
  10. 在CentOS环境中安装MySQL数据库保姆级教程
  11. 基于 PyQt 的YOLO目标检测可视化界面+ nuitka 打包
  12. 工程师 - 汽车分类
  13. 基于SpringBoot + HTML 的宠物医院预约管理
  14. 硬件工程师面试常见问题(13)
  15. TS typeof运算符
  16. TS 变量类型生成
  17. chili3d调试10 网页元素css node deepwiki 生成圆柱体 生成零件图片
  18. RabbitMQ入门基础
  19. 表驱动 FSM 在 STM32 上的高效实现与内存压缩优化——源码、性能与实践
  20. 如何从GitHub上调研优秀的开源项目,并魔改应用于工作中?
  21. 体坛联播|赵心童晋级世锦赛决赛,德布劳内一球制胜
  22. 马克思主义理论研究教学名师系列访谈|高福进:思想政治理论课要伴随时代不断更新和变化
  23. 五一假期首日,多地党政主官暗访督查节日安全和值班值守工作
  24. 西湖大学2025年上海市综合评价招生简章发布
  25. 国家卫健委对近日肖某引发舆情问题开展调查
  26. 五大光伏龙头一季度亏损超80亿元,行业冬天难言结束