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

039 Combination Sum

时间:2015-07-18 07:07:03      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:

039 Combination Sum 

这道题就是暴力搜索, 但是有个优化 就是 Line 14 处加一个 if a[s] > target 就不需要重复搜索 这样运行时间会从 236ms 变成108ms

 1 class Solution:
 2     # @param {integer[]} candidates
 3     # @param {integer} target
 4     # @return {integer[][]}
 5     def combinationSum(self, candidates, target):
 6         candidates.sort()
 7         ans = []
 8         self.help(candidates, target, [], 0, ans)
 9         return ans
10 
11     def help(self, a, target, cur, s, ans):
12         if target == 0:
13             ans.append(cur[:])
14         if target < 0 or a[s] > target:
15             return
16         while s < len(a):
17             cur.append(a[s])
18             r = self.help(a, target - a[s], cur, s, ans)
19             cur.pop()
20             s += 1

然后进一步优化 如下 line 20处 加一个 break,这样因为如果当前a[s]都已经超过target了 就没有必要继续搜索了, 这样运行时间变成 88ms 

 1 class Solution:
 2     # @param {integer[]} candidates
 3     # @param {integer} target
 4     # @return {integer[][]}
 5     def combinationSum(self, candidates, target):
 6         candidates.sort()
 7         ans = []
 8         self.help(candidates, target, [], 0, ans)
 9         return ans
10 
11     def help(self, a, target, cur, s, ans):
12         if target == 0:
13             ans.append(cur[:])
14         if target < 0 or a[s] > target:
15             return
16         while s < len(a):
17             cur.append(a[s])
18             r = self.help(a, target - a[s], cur, s, ans)
19             cur.pop()
20             if target - a[s] < 0:
21                 break
22             s += 1

 

039 Combination Sum

标签:

原文地址:http://www.cnblogs.com/dapanshe/p/4656005.html

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