39.组合总和

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

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

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

示例 1:

[2,3,6,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

方法一:搜索回溯

时间复杂度:O(S),其中S为所有可行解的长度之和

空间复杂度:O(target),除答案数组外,空间复杂度取决于递归的栈深度,在最差情况下需要递归O(target)层

复制代码
 1 /**
 2  * @param {number[]} candidates
 3  * @param {number} target
 4  * @return {number[][]}
 5  */
 6 var combinationSum = function (candidates, target) {
 7     const ans = [];
 8     const dfs = (target, combine, idx) => {
 9         if (idx === candidates.length) {
10             return;
11         }
12         if (target === 0) {
13             ans.push(combine);
14             return;
15         }
16         //直接跳过
17         dfs(target, combine, idx + 1);
18         //选择当前数
19         if (target - candidates[idx] >= 0) {
20             dfs(target - candidates[idx], [...combine, candidates[idx]], idx);
21         }
22     }
23     dfs(target, [], 0);
24     return ans;
25 };
复制代码

 

posted @   icyyyy  阅读(68)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示