LeetCode 39. 组合总和

243 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第37天,点击查看活动详情.

39. 组合总和

题目描述

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

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

对于给定的输入,保证和为 target 的不同组合数少于 150 个。 在这里插入图片描述

解题思路

思路一: 回溯

对于这类寻找所有可行解的题,我们都可以尝试用搜索回溯的方法来解决。
算法过程:

  1. 定义递归函数 dfs(target,combine,idx) 表示当前在 candidates 数组的第 idx 位,还剩 target 要组合,已经组合的列表为 combine;
  2. 递归的终止条件为 target≤0 或者 candidates 数组被全部用完; 那么在当前的函数中, 有两种处理:
    • 可以选择跳过不用第 idx 个数,即执行 dfs(target, combine,idx + 1)
    • 选择使用第 idx 个数,即执行 dfs(target − candidates[idx], combine, idx),注意到每个数字可以被无限制重复选取,因此搜索的下标仍为 idx

实现代码如下:

/**
 * @param {number[]} candidates
 * @param {number} target
 * @return {number[][]}
 */
var combinationSum = function(candidates, target) {
    const ans = [];
    // 深度遍历
    const dfs = (target, combine, idx) => {
        if (idx === candidates.length) {
            return;
        }
        // 如果刚好减到0,说明此时路径上的元素,相加等于目标元素。
        // 此时路径上的元素就符合条件,将他们加入返回结果中,并退出此次递归
        if (target === 0) {
            ans.push(combine);
            return;
        }
        dfs(target, combine, idx + 1);
        if (target - candidates[idx] >= 0) {
            dfs(target - candidates[idx], [...combine, candidates[idx]], idx);
        }
    }
    dfs(target, [], 0);
    return ans;
}; 

剪枝优化
如果 target 减去一个数得到负数,那么减去一个更大的树依然是负数,同样搜索不到结果。基于这个想法,我们可以对输入数组进行排序, 排序是为了提高搜索速度,对于解决这个问题来说非必要。但是搜索问题一般复杂度较高,能剪枝就尽量剪枝。

实现代码如下:

/**
 * @param {number[]} candidates
 * @param {number} target
 * @return {number[][]}
 */
var combinationSum = function(candidates, target) {
    let res = [];
    // 排序是剪枝的前提
    candidates.sort((a, b) => a - b);
    backtrace(candidates,target,res,[] ,0)
    return res;
};

function backtrace(candidates,target,res,ans,startIndex){
    // 如果此时目标元素经过几次深度递归,出现负值,
    // 就说明,数组中不存在能相加等于目标数组的元素集合
    if(target < 0){
        return;
    }
    if(target === 0) {
        res.push([...ans]);
        return;
    }
    // 遍历元素,这里的i 必须要跟递归层数保持一致,要不要剪枝时,会照成重复元素
    for(let i = startIndex;i < candidates.length;i++){
        if(target < candidates[i]) break;
        // //将路径上的元素加入结果集合中
        ans.push(candidates[i])
        // 递归
        // 在进行一轮剪枝到根节点的时候,下一轮的搜索的启点就不能包括上一次搜索的下标了
        // 此时在拼接重复元素的时候,起点只能是大于等于当前元素的下标。
        backtrace(candidates,target - candidates[i], res, ans, i);
        // 回溯
        // 将元素进行删除,也叫剪枝,
        // 这里必须从队列的尾部开始删除,这样才能达到从底层逐层删除
        ans.pop()
    }
}
 

参考资料

回溯算法 + 剪枝(回溯经典例题详解) - 组合总和 - 力扣(LeetCode)

组合总和 - 组合总和 - 力扣(LeetCode)