#-*-Coding:utf8-*-
‘‘‘
__author__ = ' [email protected] '
40:combination Sum II
https://oj.leetcode.com/problems/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 is used once in the combination.
Note:
All numbers (including target) would be positive integers.
Elements in a combination (A1, A2, ..., AK) must is 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]
===comments by dabay===
Recursion.
Sort the candidates first.
Traverse the candidates and use index to record the current pointer.
Note the possible duplication in the result set is removed.
‘‘‘
Class Solution:
# @param candidates, a list of integers
# @param target, Integer
# @return A list of lists of integers
def combinationSum2 (self, candidates, target):
def combinationsum (candidates, target, index, RES, res_list):
If target = = 0:
If res not in Res_list:
Res_list.append (List (res))
Return
While index < Len (candidates) and Target >= Candidates[index]:
Res.append (Candidates[index])
Combinationsum (candidates, Target-candidates[index], index+1, res, res_list)
Res.pop ()
Index + = 1
Res_list = []
Candidates.sort ()
Combinationsum (candidates, target, 0, [], res_list)
Return res_list
def main ():
Sol = solution ()
Candidates = [10,1,2,7,6,1,5]
target = 8
Print sol.combinationsum2 (candidates, target)
if __name__ = = "__main__":
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)
[Leetcode] [Python]40:combination Sum II