Eat Study Love

먹고 공부하고 사랑하라

Coding_Practice

Combination Sum(Array,Backtracking)

eatplaylove 2025. 2. 12. 11:38

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 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

해도 해도 적응이 잘 안 되는데 Backtracking..

 

공부할 때 기분이 불편해야 공부가 잘 되고 있는 것이다.

 

아는 것을 확인하지 말고, 모르는 것을 알아가는 것이 공부!

 

 

1. Python

문제 이해는 쉬운데, 역시나 Implementation이 어렵다 -_-;;

GG

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        candidates.sort()
        def backtrack(start,target,curr) -> None :
            # 여기까진 나도 생각함. Base case
            if target == 0 :
                ans.append(curr.copy()) # 항상 append 할 때는 복사본을!
                return
            # 여기까지도 난 생각함
            elif target < 0 : return
            
            for i in range(start,len(candidates)):
                curr.append(candidates[i])
                backtrack(i,target-candidates[i],curr)
                curr.pop()
        ans = []
        backtrack(0,target,[])
        return ans

 

stack을 이용하는 방법도 있다.

 

def combination_sum(numbers, target):
    results = []
    stack = [(0, [], target)]  # (start index, current combination, remaining target)

    while stack:
        start, current_combination, current_target = stack.pop()

        if current_target == 0:
            results.append(current_combination)
            continue
        if current_target < 0:
            continue

        for i in range(start, len(numbers)):
            new_combination = current_combination + [numbers[i]]
            new_target = current_target - numbers[i]
            stack.append((i, new_combination, new_target))
        print(stack)
        print(results)
    return results

# 테스트 코드
numbers = [2, 3, 6, 7]
target = 7
print(combination_sum(numbers, target))  # Expected output: [[2, 2, 3], [7]]
# numbers = [2]
# target = 8
# print(combination_sum(numbers, target))  # Expected output: [[2, 2, 2, 2]]

 

2. C++

C++은 stack을 이용해서 해봐야지

알고리즘은 비슷하다. Backtrack의 Recursive한 요소를 Stack으로 표현한 것

class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        // start idx, curr sum, temp vector
        stack<tuple<int,int,vector<int>>> s;
        vector<vector<int>> ans;
        s.push({0,0,{}});
        while(!s.empty()){
            auto [idx, curr, vec] = s.top();
            s.pop();
            if(curr==target){
                ans.push_back(vec);
                continue;
            }
            else if(curr>target) continue;

            for(int i=idx;i<candidates.size();i++){
                vector<int> temp = vec;
                temp.push_back(candidates[i]);
                s.push({i,curr+candidates[i],temp});
            }
        }
        return ans;
    }
};