LeetCode 39. Combination Sum

개발공부를해보자·2025년 2월 3일

LeetCode

목록 보기
36/95

파이썬 알고리즘 인터뷰 문제 36번(리트코드 39번) Combination Sum
https://leetcode.com/problems/combination-sum/

나의 풀이1

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        result = []

        def helper(curr, path, index):
            if curr == target:
                result.append(path[:])
                return
            if curr < target:
                for i in range(index, len(candidates)):
                    path.append(candidates[i])
                    helper(curr + candidates[i], path, i)
                    path.pop()
            return
        
        helper(0, [], 0)

        return result

나의 풀이2

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        result = []
        
        def helper(path, curr, start):
            if curr > target:
                return
            if curr == target:
                result.append(path[:])
                return
            for idx in range(start, len(candidates)):
                path.append(candidates[idx])
                helper(path, curr + candidates[idx], idx)
                path.pop()
        
        helper([], 0, 0)

        return result

다른 풀이

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        result = []
        
        def helper(path, curr, start):
            if curr > target:
                return
            if curr == target:
                result.append(path[:])
                return
            for idx in range(start, len(candidates)):
                helper(path + [candidates[idx]], curr + candidates[idx], idx)
        
        helper([], 0, 0)

        return result

다른 풀이는 책의 풀이인데 나의 풀이2와의 차이는 path를 다루는 방법이다.
나의 풀이는 생성한 path를 이용하여 추가, 제거하지만
책의 풀이는 path를 새로 생성한다.
그래서 나의 풀이가 더 좋다고 생각한다.
내가 놓친 점이 있는 것일까?

profile
개발 공부하는 30대 비전공자 직장인

0개의 댓글