标签:
题目来源
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:
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))
[LeetCode]题解(python):040-Combination Sum II
标签:
原文地址:http://www.cnblogs.com/loadofleaf/p/5025768.html