Merge pull request #250 from jojoo15/patch-24

添加 0039.组合总数 python3版本
This commit is contained in:
Carl Sun
2021-05-25 18:22:35 +08:00
committed by GitHub

View File

@ -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