JavaScript / TypeScript for LeetCode (九十六)

是差点运气,可我一直在努力!

当前进程:

  • 开始时间:2020.6.27
  • 结束时间:undefined

GitHub仓库:https://github.com/Cundefined/JavaScript-or-TypeScript-for-LeetCode

1、题目要求

( LeetCode-第39题 ) 组合总和

2、解题思路

方法:回溯法
回溯三部曲

2.1、JavaScript Solution

/**
 * @param {number[]} candidates
 * @param {number} target
 * @return {number[][]}
 */
var combinationSum = function (candidates, target) {
  if (candidates.length === 0) {
    return [];
  }

  function dfs(start, candidates, path, res, target) {
    //   递归结束条件
    if (target === 0) {
      // 深拷贝
      res.push([...path]);
      return;
    }

    for (let i = start; i < candidates.length; i++) {
      if (candidates[i] <= target) {
        //   回溯三部曲
        // 1、选择
        path.push(candidates[i]);

        // 2、从当前选择继续看下一次选还是不选
        dfs(i, candidates, path, res, target - candidates[i]);

        // 3、撤销当前选择
        path.pop();
      }
    }
  }

  const path = [];
  const res = [];

  dfs(0, candidates, path, res, target);

  return res;
};

2.2、TypeScript Solution

function combinationSum(candidates: number[], target: number): number[][] {
  if (candidates.length === 0) {
    return [];
  }

  function dfs(
    start: number,
    candidates: number[],
    path: number[],
    res: number[][],
    target: number
  ): void {
    //   递归结束条件
    if (target === 0) {
      // 深拷贝
      res.push([...path]);
      return;
    }

    for (let i: number = start; i < candidates.length; i++) {
      if (candidates[i] <= target) {
        //   回溯三部曲
        // 1、选择
        path.push(candidates[i]);

        // 2、从当前选择继续看下一次选还是不选
        dfs(i, candidates, path, res, target - candidates[i]);

        // 3、撤销当前选择
        path.pop();
      }
    }
  }

  const path: number[] = [];
  const res: number[][] = [];

  dfs(0, candidates, path, res, target);

  return res;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值