JS从给定有序数组中选取任意个数(可重复),使其和为给定值

解法

使用回溯算法完成,

遇到的坑

使用JS完成这个算法,还需要DeepCopy,使用JS的引用传递会导致list被改变

Code

/***
 * 从给定有序数组中选取任意个数(可重复),使其和为给定值
 */
class Solution {
  candidates: number[];
  target: number;
  res: number[][];
  constructor(candidates: number[], target: number){
    this.candidates = candidates
    this.target = target
    this.res = []
  }
  public combinationSum():number[][]{
    this.helper(this.candidates, this.target, [],0)
    return this.res
  }
  private helper(candidates: number[],target: number,list: number[],index: number){
    if (target<0){
      return;
    }
    if (target===0){
      /***
       *  为什么res最终是[[],[],[],[],[],[],[],[],[],[],[]]?
       *  因为没有DeepCopy list,所以在循环中被pop和push更改了
       */
      this.res.push(JSON.parse(JSON.stringify(list)))
      return;
    }
    for (let i = index; i < candidates.length; i++) {
      if (candidates[i]<=target){
        let kk = target- candidates[i]
        if (kk<0) continue;
        list.push(candidates[i])
        this.helper(candidates, kk,list,i)
        list.pop()
      }
    }
  }
}

const test = new Solution([1,2,3,4,5,6], 10)
const res = test.combinationSum()
console.log(res);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值