NO.39 组合总数Ⅰ NO.40 组合总数Ⅱ

复制代码
class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        res = []
        path = []
        n = len(candidates)
        candidates.sort()
        def backtracking(startIndex, target):
            if target==0:
                # 为后续遍历,必须append(path[:])
                res.append(path[:])  
                return
            if target<0:  # 相当于剪枝操作(若target小于零,直接停止向深度方向继续执行)
                return            
            for i in range(startIndex, n):           
                #  跳过同一层使用过的元素(必须加上这个条件i >startIndex,这样可以保证仅跳过同一层使用的元素)     
                if i >startIndex and candidates[i] == candidates[i-1]:  
                    continue #不重复使用值
                path.append(candidates[i])  
                backtracking(i+1,target-candidates[i])  # 递归
                path.pop()  # 回溯 
            return res

        return backtracking(0, target)
复制代码
复制代码
NO.39 组合总数Ⅰ

#对数组就行排序减小搜索空间
#递归的结果分为3种:1.符合则加入
#                2.不符合继续
#                3.超过则停止
#注意重复值去除,比如为[2,2,3],target=7可能返回为[2,2,3],[3,2,2]
class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        res = []
        def find(candidates,target,part_res):
            if target<0:return#三种情况
            elif target==0: return res.append(part_res)
            else:
                for i,now_num in enumerate(candidates):
                    find(candidates[i:],target-now_num,part_res+[now_num])#开始递归,[i:]保证不往前递归解决重复值,第二为所求target,第三为添加答案列表
        find(candidates,target,[]) #初始化
        return res

#动态规划
class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        dict = {}
        for i in range(1,target+1):
            dict[i]=[] #初始化字典
        
        for i in range(1,target+1):
            for j in candidates:
                if i==j: #等于直接添加
                    dict[i].append([i])
                elif i>j:# i>j说明还可以细分
                    for k in dict[i-j]: #在j-i的字典中寻找有无该值
                        x = k[:]
                        x.append(j)
                        x.sort() # 升序,便于后续去重
                        if x not in dict[i]:
                            dict[i].append(x)

        return dict[target]
复制代码

 

俩题有相似之处仅需稍微注意
 
posted @   是冰美式诶  阅读(38)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示