일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- 자바스크립트 reduce()
- 자바스크립트 split()
- 코드스테이츠
- HTML
- 프론트개발공부
- 개발일기
- 자바스크립트 날씨 웹 만들기
- 자바스크립트 sort()
- RN 프로젝트
- 엘리스 ai 트랙
- 부트캠프
- [파이썬 실습] 중급 문제
- 간단한 날씨 웹 만들기
- 엘리스 AI 트랙 5기
- 코딩부트캠프
- 자바스크립트
- 프론트개발
- 리트코드
- 개발공부
- leetcode
- [파이썬 실습] 심화 문제
- 삼항연산자
- 엘리스
- [AI 5기] 연습 문제집
- reactnativecli
- [파이썬 실습] 기초 문제
- 날씨 웹 만들기
- 프로그래머스
- JavaScript
- 자바스크립트 날씨
- Today
- Total
개발조각
[리트코드] 39. Combination Sum 본문
문제
https://leetcode.com/problems/combination-sum/
Combination Sum - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
소스코드
var combinationSum = function(candidates, target) {
let result = [];
function sumTarget(arr=[], sum=0, idx=0){
if(sum > target) return;
if(sum === target){
result.push(arr);
return;
}
for(let i= idx; i<candidates.length; i++){
sumTarget([...arr, candidates[i]], sum+candidates[i], i);
}
}
sumTarget();
return result;
};
이문제는 코드를 보고 어떻게 돌아가는지 설명을 보시면 이해가 가실 것 같아요
보이실지 잘 모르겠는데
condidates = [2, 3, 6], target=7일 경우에 돌아가는 구조입니다.
var combinationSum = function(candidates, target) {
let result = [];
function sumTarget(arr=[], sum=0, idx=0){
if(sum > target) return;
if(sum === target){
result.push(arr);
return;
}
for(let i= idx; i<candidates.length; i++){
console.log([...arr, candidates[i]], sum+candidates[i], i)
sumTarget([...arr, candidates[i]], sum+candidates[i], i);
}
}
sumTarget();
return result;
}; []
이렇게 중간에 콘솔을 찍어보면
[ 2 ] 2 0
[ 2, 2 ] 4 0
[ 2, 2, 2 ] 6 0
[ 2, 2, 2, 2 ] 8 0
[ 2, 2, 2, 3 ] 9 1
[ 2, 2, 2, 6 ] 12 2
[ 2, 2, 3 ] 7 1
[ 2, 2, 6 ] 10 2
[ 2, 3 ] 5 1
[ 2, 3, 3 ] 8 1
[ 2, 3, 6 ] 11 2
[ 2, 6 ] 8 2
[ 3 ] 3 1
[ 3, 3 ] 6 1
[ 3, 3, 3 ] 9 1
[ 3, 3, 6 ] 12 2
[ 3, 6 ] 9 2
[ 6 ] 6 2
[ 6, 6 ] 12 2
이런식으로 나오고
나누어서 설명하면 아래와 같이 되겠죠
[ 2 ] 2 0
[ 2, 2 ] 4 0
[ 2, 2, 2 ] 6 0
[ 2, 2, 2, 2 ] 8 0
[ 2, 2, 2, 3 ] 9 1
[ 2, 2, 2, 6 ] 12 2
[ 2, 2, 3 ] 7 1
[ 2, 2, 6 ] 10 2
[ 2, 3 ] 5 1
[ 2, 3, 3 ] 8 1
[ 2, 3, 6 ] 11 2
[ 2, 6 ] 8 2
[ 3 ] 3 1
[ 3, 3 ] 6 1
[ 3, 3, 3 ] 9 1
[ 3, 3, 6 ] 12 2
[ 3, 6 ] 9 2
[ 6 ] 6 2
[ 6, 6 ] 12 2
'알고리즘🅰 > 리트코드' 카테고리의 다른 글
[리트코드] 46. Permutations (0) | 2022.10.09 |
---|---|
[리트코드] 43. Multiply Strings (0) | 2022.10.08 |
[리트코드] 38. Count and Say (0) | 2022.10.03 |
[리트코드] 33. Search in Rotated Sorted Array (0) | 2022.10.01 |
[리트코드] 34. Find First and Last Position of Element in Sorted Array (0) | 2022.09.30 |