본문 바로가기
LeetCode

[LeetCode] 39. Combination Sum

by JungSeung 2023. 11. 3.
728x90

https://leetcode.com/

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 combinations in any order.

The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the 
frequency of at least one of the chosen numbers is different.

The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.

 

Example 1:

Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.

 

Example 2:

Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]

 

Example 3:

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

 

Constraints:

  • 1 <= candidates.length <= 30
  • 2 <= candidates[i] <= 40
  • All elements of candidates are distinct.
  • 1 <= target <= 40

 

Code :

var combinationSum = function(candidates, target) {
    const result = []; // 조합 결과를 저장할 배열

    function backtrack(remaining, currentCombo, start) {
        if (remaining === 0) { // 남은 값이 0인 경우
            result.push([...currentCombo]); // 현재 조합을 결과 배열에 추가
            return;
        }

        if (remaining < 0) { // 남은 값이 0보다 작은 경우
            return; // 종료
        }

        for (let i = start; i < candidates.length; i++) { // 시작 인덱스부터 후보 배열의 끝까지 반복
            currentCombo.push(candidates[i]); // 후보를 현재 조합에 추가
            backtrack(remaining - candidates[i], currentCombo, i); // 재귀적으로 탐색하여 조합 완성
            currentCombo.pop(); // 탐색 후 후보 제거 (백트래킹)
        }
    }

    backtrack(target, [], 0); // 백트래킹 함수 호출

    return result; // 결과 배열 반환
};

 

Solutions Code :

var combinationSum = function(candidates, target) {
    let index = 0; // 인덱스 변수 초기화
    let tempDataStruct = []; // 임시 데이터 구조 배열 초기화
    let result = []; // 결과 배열 초기화

    function backtracking(index, target, tempDataStruct) { // 백트래킹 함수 정의
        if(target === 0) { // 타겟이 0인 경우
            result.push([...tempDataStruct]); // 현재 임시 데이터 구조를 결과 배열에 추가
            return; // 종료
        }
    
        if(target < 0) return; // 타겟이 0보다 작은 경우 종료
    
        for(let i=index; i<candidates.length; i++) { // 후보 배열 순회
            tempDataStruct.push(candidates[i]); // 후보를 임시 데이터 구조에 추가
            backtracking(i, target-candidates[i], tempDataStruct); // 재귀적으로 탐색하여 조합 완성
            tempDataStruct.pop(); // 탐색 후 후보 제거 (백트래킹)
        }
    }
    backtracking(index, target, tempDataStruct); // 백트래킹 함수 호출
    return result; // 결과 배열 반환
};

 

 

출처 : https://leetcode.com/problemset/all/

728x90

'LeetCode' 카테고리의 다른 글

[LeetCode] 41. First Missing Positive  (0) 2023.11.07
[LeetCode] 40. Combination Sum II  (0) 2023.11.06
[LeetCode] 38. Count and Say  (0) 2023.11.02
[LeetCode] 37. Sudoku Solver  (0) 2023.11.02
[LeetCode] 36. Valid Sudoku  (0) 2023.11.02