【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.
  • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • 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. Combination Sum,唯一的区别在于本题数字只能使用一次,而不是无限次。所以我们只需要对上一题的代码稍作修改,就可以实现本题的要求。

AC代码:

class Solution(object):
    def combinationSum2(self, candidates, target):
        ret_list = []
        def backtracing(target, candidates, index, temp_list):
            if target == 0:
                ret_list.append(temp_list)
            elif target > 0:
                for i in xrange(index, len(candidates)):
                    # remove duplicates
                    if i != index and candidates[i] == candidates[i - 1]:
                        continue
                    backtracing(target - candidates[i], candidates, i + 1, temp_list + [candidates[i]])

        backtracing(target, sorted(candidates), 0, [])
        return ret_list
原文地址:https://www.cnblogs.com/zhuifengjingling/p/5294101.html