216 Combination Sum III

暴力搜索 无压力, 只是要注意Line 14作用 如果用deepcopy则耗时多了好多

 1 class Solution:
 2     def __init__(self):
 3         self.ans = []
 4     # @param {integer} k
 5     # @param {integer} n
 6     # @return {integer[][]}
 7     def combinationSum3(self, k, n):
 8         self.dummy(0, [], k, n)
 9         return self.ans
10 
11     def dummy(self, l, s, k, n):
12         if l == k:
13             if sum(s) == n:
14                 self.ans.append(list(s)) # if use ans.append(s) we should use ans.append.(copy.deepcopy) which costs more time
15             return
16         else:
17             if l == 0:
18                 start = 1
19             else:
20                 start = s[-1] + 1
21             for i in range(start, 10):
22                 s.append(i)
23                 self.dummy(l + 1, s, k, n)
24                 s.pop()

 

posted @ 2015-07-04 13:06  dapanshe  阅读(125)  评论(0编辑  收藏  举报