DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on • Edited on

Combination Sum- I


/**
 * @param {number[]} candidates
 * @param {number} target
 * @return {number[][]}
 */
var combinationSum = function(candidates, target) {

    let result = [];
    let tempArray = [];

    backTrackRecord(candidates, target, result, tempArray, 0);
    return result;
};

const backTrackRecord = (candidates, target, result, tempArray, currIndex) => {
  if (target === 0) {
    result.push([...tempArray]);
    return false;
  }
  if (target < 0) {
    return false;
  }

  for (let i = currIndex; i < candidates.length; i++) {
    tempArray.push(candidates[i]);
    backTrackRecord(candidates, target - candidates[i], result, tempArray, i);
    tempArray.pop(candidates[i]);
  }
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)