算法 - dfs/bfs/回溯


力扣 39. 组合总和

const combination = function(candidates, target) {
  const res = [];
  const dfs = function(target, combine, depth) {
    // 剪枝
    if (depth === candidates.length) {
      return;
    }
    // 目的
    if (target === 0) {
      res.push(combine);
      return;
    }
    // 直接跳过
    dfs(target, combine, depth+1);
    // 选择
    if (target - candidates[depth] >= 0) {
      dfs(target - candidates[depth], [...combine, candidates[depth]], depth)
    }
  }
}

相关