Scribbling

39. Combination Sum 본문

Computer Science/Coding Test

39. Combination Sum

focalpoint 2021. 9. 4. 19:31
class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        ret = []
        arr = [0]
        self.helper(ret, arr, candidates, target)
        return ret
        
    def helper(self, ret, arr, candidates, target):
        _sum = sum(arr)
        if _sum > target:
            return
        if _sum == target:
            ret.append(arr[1:])
            return
        for candidate in candidates:
            last_input = arr[-1]
            if candidate >= last_input:
                next_arr = arr.copy()
                next_arr.append(candidate)
                self.helper(ret, next_arr, candidates, target)

 

좀 더 좋은 solution...

본질적으로는 dfs 라는 점을 파악하면 더 쉽게 접근 가능,,,

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        ret = []
        self.dfs(candidates, target, [], ret)
        return ret
        
    def dfs(self, nums, target, path, ret):
        if target < 0:
            return
        if target == 0:
            ret.append(path)
            return
        
        for i in range(len(nums)):
            self.dfs(nums[i:], target-nums[i], path+[nums[i]], ret)

'Computer Science > Coding Test' 카테고리의 다른 글

44. Wildcard Matching  (0) 2021.09.06
LeetCode: 48. Rotate Image  (0) 2021.09.05
32. Longest Valid Parentheses  (0) 2021.09.04
LeetCode: 29. Divide Two Integers  (0) 2021.09.02
LeetCode: 50. Pow(x, n)  (0) 2021.09.02