Skip to content

Latest commit

 

History

History
95 lines (69 loc) · 1.92 KB

40.combination_sum_ii.md

File metadata and controls

95 lines (69 loc) · 1.92 KB
  1. Combination Sum II

中等

https://leetcode.cn/problems/combination-sum-ii/

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

相关企业

  • Facebook|5
  • 亚马逊 Amazon|5
  • 字节跳动|3
  • 彭博 Bloomberg|3
  • 微软 Microsoft|2
  • 甲骨文 Oracle|2

相关标签

  • Array
  • Backtracking

相似题目

  • Combination Sum 中等

sol

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

        candidatesSorted = sorted(candidates)
        results = []
        self.dfs(candidatesSorted, target, 0, [], results)
        return results

    def dfs(self, candidatesSorted, remainTarget, currIndex, currSubset, results):
        if remainTarget < 0:
            return
        if remainTarget == 0:
            results.append(list(currSubset))
            return

        for i in range(currIndex, len(candidatesSorted)):
            if i != currIndex and candidatesSorted[i] == candidatesSorted[i-1]:
                continue # 选代表 skip duplicate elements

            if remainTarget < candidatesSorted[i]:
                break
            
            currSubset.append(candidatesSorted[i])
            # each elem used only once so i+1
            self.dfs(candidatesSorted, remainTarget - candidatesSorted[i], i + 1, currSubset, results)
            currSubset.pop()