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]
相关推荐
Yingye Zhu(HPXXZYY)3 小时前
ICPC 2023 Nanjing R L 题 Elevator
算法
阿维的博客日记5 小时前
LeetCode 139. 单词拆分 - 动态规划解法详解
leetcode·动态规划·代理模式
程序员Xu6 小时前
【LeetCode热题100道笔记】二叉树的右视图
笔记·算法·leetcode
笑脸惹桃花7 小时前
50系显卡训练深度学习YOLO等算法报错的解决方法
深度学习·算法·yolo·torch·cuda
阿维的博客日记7 小时前
LeetCode 48 - 旋转图像算法详解(全网最优雅的Java算法
算法·leetcode
GEO_YScsn7 小时前
Rust 的生命周期与借用检查:安全性深度保障的基石
网络·算法
程序员Xu8 小时前
【LeetCode热题100道笔记】二叉搜索树中第 K 小的元素
笔记·算法·leetcode
THMAIL9 小时前
机器学习从入门到精通 - 数据预处理实战秘籍:清洗、转换与特征工程入门
人工智能·python·算法·机器学习·数据挖掘·逻辑回归
Kevinhbr9 小时前
CSP-J/S IS COMING
数据结构·c++·算法
蕓晨9 小时前
set的插入和pair的用法
c++·算法