码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-12-07 14:13:02      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:


题目来源


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)

 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             Solution.ans.append(valueList)
 8         length = len(candidates)
 9         for i in range(start, length):
10             if candidates[i] > target:
11                 return
12             self.find(candidates, target - candidates[i], i, valueList + [candidates[i]])
13 
14     def combinationSum(self, candidates, target):
15         """
16         :type candidates: List[int]
17         :type target: int
18         :rtype: List[List[int]]
19         """
20         candidates.sort()
21         Solution.ans = []
22         self.find(candidates, target, 0, [])
23         return Solution.ans
24 
25 s = Solution()
26 candidates = [2,3,6,7]
27 target = 7
28 print(s.combinationSum(candidates, target))

 

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

标签:

原文地址:http://www.cnblogs.com/loadofleaf/p/5025742.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!