[Leetcode] [Python]40:combination Sum II

Source: Internet
Author: User

#-*-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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.