Leetcode 40. Combination Sum II

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

Each number in C 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.

For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,
A solution set is:

[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]
 

这道题和Leetcode 39差不多,区别是一个元素只能用一次,所以L27里面用了candidates[i+1:]。另外需要注意的是,[1a,2,5] 和 [1b,2,5]在结果中应被视为重复解而去掉一个。所以用了L13-L16。

 1 class Solution(object):
 2     def combinationSum2(self, candidates, target):
 3         """
 4         :type candidates: List[int]
 5         :type target: int
 6         :rtype: List[List[int]]
 7         """
 8         candidates.sort()
 9         
10         res = []
11         self.helper(candidates, target, res, [])
12         
13         ans = []
14         for elem in res:
15             if elem not in ans:
16                 ans.append(elem)
17         
18         return ans
19         
20     def helper(self, candidates, target, res, line):
21         if target == 0:
22             res.append([x for x in line])
23         
24         for i,x in enumerate(candidates):
25             if x <= target:
26                 line.append(x)
27                 self.helper(candidates[i+1:], target - x, res, line)
28                 line.pop()
29     

 

posted @ 2017-01-05 04:11  lettuan  阅读(141)  评论(0编辑  收藏  举报