[LeetCode]题解(python):039-Combination Sum


题目来源


https://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 may be chosen from C unlimited number of times.


题意分析


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 2,3,6,7 and target 7
A solution set is: 
[7] 
[2, 2, 3]


题目思路


先对list进行排序,然后穷举即可


AC代码(Python)

 _author_ = "YE"
# -*- coding:utf-8 -*- class Solution(object):
def find(self,candidates, target, start, valueList):
if target == 0:
Solution.ans.append(valueList)
length = len(candidates)
for i in range(start, length):
if candidates[i] > target:
return
self.find(candidates, target - candidates[i], i, valueList + [candidates[i]]) def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
Solution.ans = []
self.find(candidates, target, 0, [])
return Solution.ans s = Solution()
candidates = [2,3,6,7]
target = 7
print(s.combinationSum(candidates, target))
上一篇:配置Pycharm3.4.1调试edX Devstack


下一篇:IPSEC -配置方式