Leetcode Day21组合总和

39 元素可重复选

输入:candidates = 2,3,6,7, target = 7

输出:\[2,2,3,7]

可以重复选, 代表for j in range(start, n)中, 下一个dfs起点可以是j, 这样代表了重复选择, 但是如何保证不会死循环呢, 就需要利用都是正数的条件了

python 复制代码
class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        ans = []
        def dfs(path, partial_sum, start):
            if partial_sum > target:
                return
            if partial_sum == target:
                ans.append(path[:])
                return 
            for j in range(start, len(candidates)):
                path.append(candidates[j])
                dfs(path, partial_sum + candidates[j], j)
                path.pop()
        dfs([], 0, 0)
        return ans

39 nums中有重复, 但每个只能选一次

输入: candidates = 10,1,2,7,6,1,5, target = 8,

输出:

\[1,1,6\], \[1,2,5\], \[1,7\], \[2,6

]

只用添加两个改变, 横向去重和下一个的开始index会变为j + 1

python 复制代码
class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        ans = []
        candidates.sort()
        def dfs(path, partial_sum, start):
            if partial_sum > target:
                return
            if partial_sum == target:
                ans.append(path[:])
                return
            for j in range(start, len(candidates)):
                if j > start and candidates[j] == candidates[j - 1]:
                    continue
                path.append(candidates[j])
                dfs(path, partial_sum + candidates[j], j + 1)
                path.pop()
        dfs([], 0, 0)
        return ans

377

输入:nums = 1,2,3, target = 4

输出:7

解释:

所有可能的组合为:

(1, 1, 1, 1)

(1, 1, 2)

(1, 2, 1)

(1, 3)

(2, 1, 1)

(2, 2)

(3, 1)

python 复制代码
class Solution:
    def combinationSum4(self, nums: List[int], target: int) -> int:
        dp = [1] + [0] * target
        for i in range(1, len(dp)):
            for num in nums:
                if num > target:
                    continue
                dp[i] += dp[i - num]
        return dp[-1]
相关推荐
爱跳舞的烤冷面12 分钟前
自学嵌入式第22天(数据结构——哈希)
数据结构·算法·哈希算法
猎嘤一号32 分钟前
博弈论(Game Theory)的理论、算法与工程
人工智能·算法·安全·博弈论
马拉AI1 小时前
腾讯开源 Agent 记忆系统,AI“换对话就忘”的问题有了新解法(附安装使用教程)
人工智能·算法·开源·科研
地平线开发者2 小时前
征程6工具链模型X86推理方式说明
算法
地平线开发者3 小时前
【征程6】校准量化中HistogramObserver解析
算法
OuO-23 小时前
笔试强训 Day 34:ISBN 号码、kotori 和迷宫、矩阵最长递增路径
java·算法·矩阵
程序喵大人4 小时前
【C++进阶】STL算法与函数对象 - 04 find、count和any_of把查询写成意图
开发语言·c++·算法
豆沙沙包?4 小时前
c++中引用(P7-P11)
java·c++·算法
不会代码的小猴5 小时前
标准模板库(STL)
开发语言·c++·笔记·算法
ZhouDevin5 小时前
算法论文/高效微调4——DoRA:权重分解的低秩适配方法
算法