LeetCode - 39. Combination Sum (Python)

조민수·2024년 6월 6일
0

LeetCode

목록 보기
21/61

Medium, 백트래킹

RunTime : 67 ms / Memory : 16.58 MB


문제

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.


풀이

  • 백준 N과 M 과 유사한 문제 인거 같음
  • 실버 2~3 정도 되지 않을까
class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        res = []
        candidates.sort()

        if not candidates or min(candidates) > target:
            return []
        
        def dfs(idx, out):
            if sum(out) == target:
                res.append(out[:])
                return
            elif sum(out) > target:
                return
            
            for i in range(idx, len(candidates)):
                out.append(candidates[i])
                dfs(i, out)
                out.pop()

        dfs(0, [])
        return res
profile
사람을 좋아하는 Front-End 개발자

0개의 댓글