티스토리 뷰

cs/알고리즘

leetCode - Combination Sum

vivelakorea 2021. 3. 13. 17:27

leetcode.com/problems/combination-sum

 

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        
        def DFS(node, combination, summation):
            combination.append(node)
            summation += node
            if summation == target:
                combinations.append(combination[:])
                summation -= combination.pop()
                return
            for child in [child for child in deq_candidates if child >= node and child + summation <= target]:
                DFS(child, combination, summation)
            summation -= combination.pop()
            
        combinations = []
        
        candidates.sort()
        n_candidates = len(candidates)
        deq_candidates = collections.deque(candidates)
    
        for i in range(n_candidates):
            combination = []
            DFS(candidates[i], combination, 0)
            deq_candidates.popleft()
            
        return combinations

 

순열이 아닌 조합을 찾을 때는

1. 오름차순으로 정리

2. 자식 노드들을 부모 노드 이상의 노드들로 구성

하면 된다.

'cs > 알고리즘' 카테고리의 다른 글

leetCode - Network Delay Time  (0) 2021.03.21
leetCode - Subsets  (0) 2021.03.13
leetCode - Combinations  (0) 2021.03.13
leetCode - Permutations  (0) 2021.03.11
leetCode - Letter Combinations of a Phone Number  (0) 2021.03.11
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함