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]
相关推荐
数研小生2 小时前
构建命令行单词记忆工具:JSON 词库与艾宾浩斯复习算法的完美结合
算法·json
芒克芒克2 小时前
LeetCode 题解:除自身以外数组的乘积
算法·leetcode
Python 老手2 小时前
Python while 循环 极简核心讲解
java·python·算法
@Aurora.2 小时前
优选算法【专题九:哈希表】
算法·哈希算法·散列表
爱看科技3 小时前
微美全息(NASDAQ:WIMI)研究拜占庭容错联邦学习算法,数据安全与隐私保护的双重保障
算法
qq_417129253 小时前
C++中的桥接模式变体
开发语言·c++·算法
YuTaoShao3 小时前
【LeetCode 每日一题】3010. 将数组分成最小总代价的子数组 I——(解法二)排序
算法·leetcode·排序算法
XH华5 小时前
备战蓝桥杯,第七章:函数与递归
职场和发展·蓝桥杯
吴维炜5 小时前
「Python算法」计费引擎系统SKILL.md
python·算法·agent·skill.md·vb coding
Σίσυφος19006 小时前
PCL Point-to-Point ICP详解
人工智能·算法