Advertisement
jinhuang1102

39. Combination Sum

Apr 12th, 2019
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.94 KB | None | 0 0
  1. """
  2. 39. Combination Sum
  3. 这道题是一道很典型的backtrack的题。backtrack写起来首先就是要写出来return的条件,
  4. 1. 当违反递归规则时,直接return。
  5. 2. 当符合递归规则时,将求解写到result中。
  6. 然后执行递归。
  7. 注意递归时的传入参数
  8. """
  9.  
  10. class Solution(object):
  11.     def backtrack(self, ls, idx, tmp, val, res):
  12.         if val < 0:
  13.             return
  14.        
  15.         if val == 0:
  16.             res.append(tmp)
  17.             return
  18.        
  19.         for i in range(idx, len(ls)):
  20.             self.backtrack(ls, i, tmp + [ls[i]], val - ls[i], res)
  21.            
  22.         return
  23.    
  24.     def combinationSum(self, candidates, target):
  25.         """
  26.        :type candidates: List[int]
  27.        :type target: int
  28.        :rtype: List[List[int]]
  29.        """
  30.         res = []
  31.         candidates.sort()
  32.        
  33.         self.backtrack(candidates, 0, [], target, res)
  34.        
  35.         return res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement