From 340277131853eefaf669a47a7b092227632e71f9 Mon Sep 17 00:00:00 2001 From: jojoo15 <75017412+jojoo15@users.noreply.github.com> Date: Tue, 25 May 2021 10:16:43 +0200 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200039.=E7=BB=84=E5=90=88?= =?UTF-8?q?=E6=80=BB=E6=95=B0=20python3=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0039.组合总数 python3版本 --- problems/0039.组合总和.md | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) 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: