From 8fb77f425182ad1c6ebd476eedcea6c779666d13 Mon Sep 17 00:00:00 2001 From: jojoo15 <75017412+jojoo15@users.noreply.github.com> Date: Tue, 25 May 2021 11:08:42 +0200 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200040.=E7=BB=84=E5=90=88?= =?UTF-8?q?=E6=80=BB=E5=92=8C=E2=85=A0=E2=85=A0=20python3=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0040.组合总和ⅠⅠ python3版本 --- problems/0040.组合总和II.md | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/problems/0040.组合总和II.md b/problems/0040.组合总和II.md index 8ff31695..4d2996f5 100644 --- a/problems/0040.组合总和II.md +++ b/problems/0040.组合总和II.md @@ -292,10 +292,26 @@ class Solution { } } ``` - Python: - - +```python3 +class Solution: + def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: + res = [] + path = [] + def backtrack(candidates,target,sum,startIndex): + if sum == target: res.append(path[:]) + for i in range(startIndex,len(candidates)): #要对同一树层使用过的元素进行跳过 + if sum + candidates[i] > target: return + if i > startIndex and candidates[i] == candidates[i-1]: continue #直接用startIndex来去重,要对同一树层使用过的元素进行跳过 + sum += candidates[i] + path.append(candidates[i]) + backtrack(candidates,target,sum,i+1) #i+1:每个数字在每个组合中只能使用一次 + sum -= candidates[i] #回溯 + path.pop() #回溯 + candidates = sorted(candidates) #首先把给candidates排序,让其相同的元素都挨在一起。 + backtrack(candidates,target,0,0) + return res +``` Go: