LeetCode Combination Sum || (JavaScript), BackTracking

2025. 11. 25. 18:23·코딩테스트/LeetCode

링크 : https://leetcode.com/problems/combination-sum-ii/

문제 설명

더보기
더보기

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.

Each number in candidates may only be used once in the combination.

Note: The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8
Output:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]

Example 2:

Input: candidates = [2,5,2,1,2], target = 5
Output:
[
[1,2,2],
[5]
]

Constraints:

  • 1 <= candidates.length <= 100
  • 1 <= candidates[i] <= 50
  • 1 <= target <= 30

문제 풀이

https://kuh97.tistory.com/entry/LeetCode-Combination-Sum-JavaScript-BackTracking

 

LeetCode Combination Sum (JavaScript), BackTracking

링크 : https://leetcode.com/problems/combination-sum/description/문제 설명더보기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 targ

kuh97.tistory.com

위 사이트 설명 참고

+ 추가 된 내용

  • 후보는 한 번씩만 선택되어야 되고 중복이 되면 안된다. -> 시작지점 부터 검사를 진행할 때 그 이후에 같은 숫자가 나오면 건너뛰도록 해야 중복된 값이 안나옴
  • Output은 정렬이 되어 있다. -> 처음에 candidates를 sort

 

중복된 값 예시

[1, 1, 2, 5, 6, 7, 10] / 8인 상황에서

[1, 2, 5] 가 정답으로 만들어지는데 `if (i > index && (candidates[i - 1] === candidates[i])) continue;`를 추가 안하게 되면 다음과 같은 상황에서 중복으로 생성이 됨

  • [1, 1, 2, 5, 6, 7, 10]
  • [1, 1, 2, 5, 6, 7, 10]

이와 같은 상황을 처리하기위해 같은 depth인 경우 i를 기준으로 i - 1 === i 이번 건너 뛰도록해서 중복을 처리

/**
 * @param {number[]} candidates
 * @param {number} target
 * @return {number[][]}
 */
var combinationSum2 = function(candidates, target) {
    const answer = [];
    candidates.sort((a, b) => a - b);

    const backtracking = (index, sum, selected) => {
        if (sum === target) {
            answer.push([...selected]);
            return;
        }

        for (let i = index; i < candidates.length; i++) {
            if (i > index && (candidates[i - 1] === candidates[i])) {
                continue;
            }

            if (sum + candidates[i] <= target) {
                selected.push(candidates[i]);
                backtracking(i + 1, sum + candidates[i], selected);
                selected.pop();
            }
        }
    }

    backtracking(0, 0, []);

    return answer;
};

결론

중복된 값을 처리하기 위한 로직을 설정하는게 중요

'코딩테스트 > LeetCode' 카테고리의 다른 글

LeetCode Jump Game || (JavaScript), bfs/greedy  (0) 2025.11.25
LeetCode Multiply Strings (JavaScript)  (0) 2025.11.25
LeetCode Combination Sum (JavaScript), BackTracking  (0) 2025.11.25
LeetCode Count and Say (JavaScript)  (0) 2025.11.25
LeetCode Valid Sudoku (JavaScript), Set  (0) 2025.11.24
'코딩테스트/LeetCode' 카테고리의 다른 글
  • LeetCode Jump Game || (JavaScript), bfs/greedy
  • LeetCode Multiply Strings (JavaScript)
  • LeetCode Combination Sum (JavaScript), BackTracking
  • LeetCode Count and Say (JavaScript)
의현
의현
개발하는 하루
  • 의현
    UIHYEON
    의현
  • 링크

    • 김의현 포트폴리오
    • GitHub
    • LinkedIn
  • 전체
    오늘
    어제
    • 분류 전체보기 (218)
      • 프론트엔드 (65)
        • JavaScript (52)
        • HTML (3)
        • React (7)
        • CSS (2)
        • CS (1)
      • 프로젝트 (19)
        • Portfolio 사이트 개발 (19)
      • 코딩테스트 (131)
        • Binary Search (2)
        • bfs (Breadth-first s.. (4)
        • dfs (Deapth-first se.. (1)
        • Greedy (1)
        • Dynamic Programming (1)
        • two pointer (4)
        • 구현 (2)
        • LIS(Longest Increasi.. (0)
        • 문자열 (3)
        • 자료구조 (6)
        • 비트마스크 (2)
        • 수학 (2)
        • 프로그래머스 (61)
        • LeetCode (42)
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
의현
LeetCode Combination Sum || (JavaScript), BackTracking
상단으로

티스토리툴바