Ray-56 / like-algorithms

每天一道算法题,突破自己
2 stars 1 forks source link

✅39. 组合总和 #149

Open Ray-56 opened 3 years ago

Ray-56 commented 3 years ago

39. 组合总和

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取。

说明:

示例 1:

输入:candidates = [2,3,6,7], target = 7,
所求解集为:
[
  [7],
  [2,2,3]
]

示例 2:

输入:candidates = [2,3,5], target = 8,
所求解集为:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

提示:

Ray-56 commented 3 years ago

深度递归,以[2, 3, 5]举例

2开始

/**
 * @param {number[]} candidates
 * @param {number} target
 * @return {number[][]}
 */
var combinationSum = function(candidates, target) {
    const ret = [];
    dfs(target, [], 0);
    function dfs(target, combine, index) {
        if (index >= candidates.length) return;
        if (target === 0) {
            ret.push(combine);
            return;
        }

        // 不选当前
        dfs(target, combine, index + 1);

        // 满足条件,选择当前
        if (target - candidates[index] >= 0) {
            dfs(target - candidates[index], [...combine, candidates[index]], index);
        }
    }

    return ret;
};