【每日一题】LeetCode 39. 组合总和 TypeScript

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。

对于给定的输入,保证和为 target 的不同组合数少于 150 个。

示例 1:

复制代码
输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。

示例 2:

复制代码
输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]

示例 3:

复制代码
输入: candidates = [2], target = 1
输出: []

提示:

  • 1 <= candidates.length <= 30
  • 2 <= candidates[i] <= 40
  • candidates 的所有元素 互不相同
  • 1 <= target <= 40

回溯

TypeScript 复制代码
function combinationSum(candidates: number[], target: number): number[][] {
   const res:number[][] = []
   const path:number[] = []
   candidates.sort((a,b)=>a-b)

   const track = (start:number, remain:number):void =>{
    if(remain===0){
        res.push([...path])
        return
    }
    for(let i=start;i<candidates.length;i++){
        if(candidates[i]>remain) break
        path.push(candidates[i])
        track(i,remain-candidates[i])
        path.pop()
    }
   }
   track(0,target)
   return res
};

共勉

相关推荐
zander2586 小时前
LeetCode 300. 最长递增子序列
算法·leetcode·深度优先
欧叶冲冲冲6 小时前
Python常见数据结构的CRUD(LeetCode高频版速查)
数据结构·python·leetcode
祖力556 小时前
Linux应用软件编程:目录IO与framebuffer
linux·运维·算法·framebuffer·目录io
名字还没想好☜6 小时前
Go 用 slices/maps 标准库泛型函数:告别手写 Contains、Sort、去重(Go 1.21)
开发语言·后端·算法·golang·go
古夕6 小时前
Vue 3 严格模式下,可选接口字段为什么会炸:一次上架页 TypeScript 复盘
typescript
地平线开发者6 小时前
【模型轻量化专题】深度学习模型为什么需要轻量化
算法
圣保罗的大教堂6 小时前
leetcode 3622. 判断整除性 简单
leetcode
_Narcissus_7 小时前
链表算法题和静态链表
数据结构·c++·笔记·算法·链表·ai·力扣
Lyyaoo.7 小时前
【普通数组】【中等】除了自身以外数组的乘积
数据结构·算法·leetcode
threerocks7 小时前
《The AI-Native SDLC Playbook》万字拆解
算法·aigc·ai编程