diff --git a/problems/0039.组合总和.md b/problems/0039.组合总和.md index d025eaef..e3e79295 100644 --- a/problems/0039.组合总和.md +++ b/problems/0039.组合总和.md @@ -271,8 +271,25 @@ class Solution { ``` Python: - - +```python3 +class Solution: + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: + res = [] + path = [] + def backtrack(candidates,target,sum,startIndex): + if sum > target: return + if sum == target: return res.append(path[:]) + for i in range(startIndex,len(candidates)): + if sum + candidates[i] >target: return #如果 sum + candidates[i] > target 就终止遍历 + sum += candidates[i] + path.append(candidates[i]) + backtrack(candidates,target,sum,i) #startIndex = i:表示可以重复读取当前的数 + sum -= candidates[i] #回溯 + path.pop() #回溯 + candidates = sorted(candidates) #需要排序 + backtrack(candidates,target,0,0) + return res +``` Go: