一道非常有趣的算法题分享:LeetCode39.组合总和

1,249 阅读1分钟

在leetCode中看到一道题目,非常有意思 题目为: 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

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

引用leetCode中其他人画的图来分析

引用js解法中秦时明月解题思路与步骤

var combinationSum = function (candidates, target) {
  // 由大到小排序
  candidates.sort((a, b) => b - a);

  let res = [], path = [];
  let len = candidates.length, minNum = candidates[len - 1]; // 缓存长度
  console.log(0, candidates, len, minNum)
  get_combin(candidates, target, 0, path);

  function get_combin(candidates, target, start, path) {
    console.log(1, target, start, path)
    if (target == 0) {
      return res.push(path.slice());
    }

    // 这里不用小于 0,小于最小的数就可以返回了
    if (target < minNum) return;

    for (let i = start; i < len; i++) {
      console.log(2, i, start)
      path.push(candidates[i]);
      console.log(3, path)
      get_combin(candidates, target - candidates[i], i, path);
      console.log(4, path)
      path.pop();
      console.log(5, path)
    }
  }
  console.log(6, res)
  return res;
};
combinationSum([2, 5, 6, 7], 7)