반응형
1. 문제
https://leetcode.com/problems/combination-sum/
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;
};
반응형
'리트코드 > midium' 카테고리의 다른 글
[리트코드] 215. Kth Largest Element in an Array (0) | 2023.08.09 |
---|---|
[리트코드] 49. Group Anagrams - js (0) | 2023.08.08 |
[리트코드] 230. Kth Smallest Element in a BST - js (0) | 2023.07.20 |
[리트코드] 48. Rotate Image - js (0) | 2023.07.14 |
[리트코드] 22. Generate Parentheses - js (0) | 2023.07.13 |