LeetCode Combination Sum
阿新 • • 發佈:2017-08-08
return elf 依次 ati span main var int -c
LeetCode解題之Combination Sum
原題
在一個集合(沒有反復數字)中找到和為特定值的全部組合。
註意點:
- 全部數字都是正數
- 組合中的數字要依照從小到大的順序
- 原集合中的數字可以出現反復多次
- 結果集中不可以有反復的組合
- 盡管是集合,但傳入的參數類型是列表
樣例:
輸入: candidates = [2, 3, 6, 7], target = 7
輸出: [[2, 2, 3], [7]]
解題思路
採用回溯法。
因為組合中的數字要按序排列,我們先將集合中的數排序。依次把數字放入組合中,因為全部數都是正數,假設當前和已經超出目標值,則放棄。假設和為目標值。則添加結果集;假設和小於目標值。則繼續添加元素。因為結果集中不同意出現反復的組合,所以添加元素時僅僅添加當前元素及之後的元素。
AC源代碼
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
if not candidates:
return []
candidates.sort()
result = []
self.combination(candidates, target, [], result)
return result
def combination(self, candidates, target, current, result):
s = sum(current) if current else 0
if s > target:
return
elif s == target:
result.append(current)
return
else:
for i, v in enumerate(candidates):
self.combination(candidates[i:], target, current + [v], result)
if __name__ == "__main__":
assert Solution().combinationSum([2, 3, 6, 7], 7) == [[2, 2, 3], [7]]
歡迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 來獲得相關源代碼。
LeetCode Combination Sum