엔지니어 게시판
LeetCode 솔루션 분류

[interview] 40. Combination Sum II

컨텐츠 정보

본문

Medium
6774167Add to ListShare

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.

Each number in candidates may only be used once in the combination.

Note: The solution set must not contain duplicate combinations.

 

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8
Output: 
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]

Example 2:

Input: candidates = [2,5,2,1,2], target = 5
Output: 
[
[1,2,2],
[5]
]

 

Constraints:

  • 1 <= candidates.length <= 100
  • 1 <= candidates[i] <= 50
  • 1 <= target <= 30
Accepted
636,746
Submissions
1,199,081

관련자료

댓글 1

학부유학생님의 댓글

  • 익명
  • 작성일
class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        candidates = sorted(candidates)
        res = []
        
        print(candidates)
        
        # def backtracking(i, part_sum):
        def backtracking(i, part_sum):
            # if partsum == target: append
            if sum(part_sum) == target: 
                res.append(part_sum.copy())
                return
            # part_sum > target: return
            if sum(part_sum) > target or i >= len(candidates): return
            
            # case 1. include curr i -> backtracking(i+1, part_sum)
            part_sum.append(candidates[i])
            backtracking(i+1, part_sum)
            
            
            # case 2. X include curr i
            # skip = curr[i]
            # while curr[i] == skip: i+= 1
            skip = part_sum.pop()
            while i < len(candidates) and skip == candidates[i]:
                i += 1

            backtracking(i, part_sum)
            
            
        backtracking(0, [])
        return res
전체 194 / 6 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


알림 0