본문 바로가기

리트코드/midium

[리트코드] 39. Combination Sum - js

반응형

1. 문제

https://leetcode.com/problems/combination-sum/

 

Combination Sum - LeetCode

Can you solve this real interview question? Combination Sum - Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the comb

leetcode.com

2. 코드

/**
 * @param {number[]} candidates
 * @param {number} target
 * @return {number[][]}
 */
function arraysAreEqual(arr1, arr2) {
  if (arr1.length !== arr2.length) {
    return false;
  }
  
  for (let i = 0; i < arr1.length; i++) {
    if (arr1[i] !== arr2[i]) {
      return false;
    }
  }
  
  return true;
}

var combinationSum = function(candidates, target) {
    let answer = [];

    const check = (candidate, sum) => {
        if(sum === target){
            let same = answer.filter ((el) => arraysAreEqual(el,candidate));
            if(!same.length) answer.push(candidate);
        } 
        else{
            for(let i=0;i<candidates.length;i++){
                let newCandidate = candidate.slice();
                newCandidate.push(candidates[i]);
                let newSum = sum + candidates[i];
                if(newSum <= target) check(newCandidate.sort(),newSum);
            }
        }

    }

    check([],0);

    return answer;
};
반응형