Skip to content

Latest commit

 

History

History
76 lines (58 loc) · 1.72 KB

0040._combination_sum_ii.md

File metadata and controls

76 lines (58 loc) · 1.72 KB

40. Combination Sum II

难度: Medium

刷题内容

原题连接

内容描述

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

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

Note:

All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]
Example 2:

Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
  [1,2,2],
  [5]
]

解题方案

思路 1 - 时间复杂度: O(2^n)- 空间复杂度: O(2^n)******

Combination Sum 已经AC,做了minor change.

  • 递归取了当前这个数的时候idx也要从idx+1开始了
  • 要判断combo not in resappendres中去
class Solution(object):
    def combinationSum2(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        def helper(remain, combi, idx):
            if remain < 0:
                return 
            if remain == 0 and combi not in res:
                res.append(combi)
                return
            if idx >= len(candidates):
                return
            helper(remain, combi, idx+1)
            helper(remain-candidates[idx], combi+[candidates[idx]], idx+1)
        
        res = []
        candidates.sort()
        helper(target, [], 0)
        return res