#-*-Coding:utf8-*-
‘‘‘
__author__ = ' [email protected] '
39:combination Sum
https://oj.leetcode.com/problems/combination-sum/
Given a set of candidate numbers (C) and a target number (T),
Find all unique combinations in C where the candidate numbers sums to T.
The same repeated number is chosen from C unlimited number of times.
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 2,3,6,7 and Target 7,
A Solution set is:
[7]
[2, 2, 3]
===comments by dabay===
Recursion.
Sort the candidates first.
Traverse the candidates and use index to record the current pointer.
‘‘‘
Class Solution:
# @param candidates, a list of integers
# @param target, Integer
# @return A list of lists of integers
def combinationsum (self, candidates, target):
def combinationSum2 (candidates, target, index, RES, res_list):
If target = = 0:
Res_list.append (List (res))
Return
While index < Len (candidates) and Target >= Candidates[index]:
Res.append (Candidates[index])
CombinationSum2 (candidates, Target-candidates[index], index, RES, res_list)
Res.pop ()
Index + = 1
Res_list = []
Candidates.sort ()
COMBINATIONSUM2 (candidates, target, 0, [], res_list)
Return res_list
def main ():
Sol = solution ()
Candidates = [up]
target = 4
Print sol.combinationsum (candidates, target)
if __name__ = = "__main__":
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)
[Leetcode] [Python]39:combination Sum