题目来源
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 may only be used once in the combination.
题意分析
Input: a list as candidates, a value named target
Output:the list number that sumed to target
Conditions:在list里面找若干个数,使得和为target,注意每个数可以取一次
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]
题目思路
与上题类似,先对list进行排序,然后穷举即可,注意可能会出现重复情况,所以需要去重(加一个判断语句),另外注意传递时的参数的范围
AC代码(Python)
1 _author_ = "YE" 2 # -*- coding:utf-8 -*- 3 4 class Solution(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) 10 for i in range(start, length): 11 if candidates[i] > target: 12 return 13 self.find(candidates, target - candidates[i], i + 1, valueList + [candidates[i]]) 14 15 def combinationSum2(self, candidates, target): 16 """ 17 :type candidates: List[int] 18 :type target: int 19 :rtype: List[List[int]] 20 """ 21 candidates.sort() 22 Solution.ans = [] 23 self.find(candidates, target, 0, []) 24 return Solution.ans 25 26 candidates = [10,1,2,7,6,1,5] 27 target = 8 28 s = Solution() 29 print(s.combinationSum2(candidates,target))
时间: 2024-11-01 11:23:56