Source of the topic
https://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.
Test instructions Analysis
Input:a list as candidates, a value named target
Output:the list number, sumed to target
Conditions: Find a number in the list, make and for target, note that each number can be taken once
Note:
- All numbers (including target) would be positive integers.
- Elements in a combination (a1, a 2, ..., aK) must is in non-descending order. (ie, a1≤ a2≤ ... ≤ ak).
- The solution set must not contain duplicate combinations.
For example, given candidate set and 10,1,2,7,6,1,5 target 8 ,
A Solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
Topic ideas
Similar to the previous question, the list is sorted first, then the poor lift, note that there may be duplication, so you need to go to the weight (plus a judgment statement), but also pay attention to the scope of the parameters passed
AC Code (PYTHON)
1 _author_ = "YE" 2 #-*-Coding:utf-8-*-3 4 classsolution (Object): 5 def find (self,candidates, Target, start, valueList): 6 if target = = 0:7 If ValueList not in solution.ans:8 Solution.ans.append (valueList) 9 length = Len (candidates) Ten for I in range (start, length): One-candidates[i] > target:12 return13 self.find (candidates, Target-candidates[i], i + 1, valueList + [candidates[i]]) + def combinationSum2 (self, candidates, target): 16 "" "17:type candidates:list[int]18:type target:int19:rtype:list[list[int]]20" "" Candidates.sort () Solutio N.ans = []23 self.find (candidates, target, 0, []) solution.ans25 = [candidates] c14>]27 target = 828 s = solution () print (s.combinationsum2 (candidates,target)) /c10>
[Leetcode] (python): 040-combination Sum II