码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 216. Combination Sum III

时间:2017-01-05 07:52:24      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:add   app   strong   iii   str   ber   enum   should   pen   

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

 

Example 1:

Input: k = 3, n = 7

Output:

[[1,2,4]]

 

Example 2:

Input: k = 3, n = 9

Output:

[[1,2,6], [1,3,5], [2,3,4]]

这一题和combiantion sum I/II 其实很类似。只不过candidates只有[1,2,...,9]。而且只有当len(line) == k 并且 sum(line) = n才把line添加到res里面。

 1 class Solution(object):
 2     def combinationSum3(self, k, n):
 3         """
 4         :type k: int
 5         :type n: int
 6         :rtype: List[List[int]]
 7         """
 8         nums = list(range(1,10))
 9         res = []
10         self.helper(nums, k, n, res, [])
11         return res
12         
13     def helper(self, nums, k, target, res, line):
14         if target == 0 and len(line) == k:
15             res.append([x for x in line])
16         
17         for i, x in enumerate(nums):
18             if x <= target:
19                 line.append(x)
20                 self.helper(nums[i+1:], k, target -x, res, line)
21                 line.pop()

 

Leetcode 216. Combination Sum III

标签:add   app   strong   iii   str   ber   enum   should   pen   

原文地址:http://www.cnblogs.com/lettuan/p/6250986.html

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