알고리즘 문제/Leetcode

40. Combination Sum II

BEstyle 2023. 3. 5. 06:41

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

#https://leetcode.com/problems/combination-sum-ii/description/

'''
1. 아이디어 :
    모든 경우의 수를 구해야한다. 백트래킹을 사용
2. 시간복잡도 :
    O(2^n)
    해당 숫자를 포함할지, 안할지를 선택
3. 자료구조 :
    배열
'''


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

        ans = []
        temp = []
        candidates.sort()
        def backtracking(pos, cnt):
            if cnt>target:
                return
            if cnt==target:
                ans.append(temp.copy())
                return

            prev=-1
            for i in range(pos, len(candidates)):
                if candidates[i]==prev:
                    continue
                temp.append(candidates[i])
                backtracking(i+1, cnt+candidates[i])
                temp.pop()
                prev = candidates[i]


        backtracking(0,0)
        return ans