Update 0216.组合总和III.md

This commit is contained in:
jianghongcheng
2023-05-26 02:17:43 -05:00
committed by GitHub
parent 2f86a5ce27
commit 343e0775eb

View File

@ -360,28 +360,25 @@ class Solution {
```py
class Solution:
def __init__(self):
self.res = []
self.sum_now = 0
self.path = []
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
result = [] # 存放结果集
self.backtracking(n, k, 0, 1, [], result)
return result
def combinationSum3(self, k: int, n: int) -> [[int]]:
self.backtracking(k, n, 1)
return self.res
def backtracking(self, targetSum, k, currentSum, startIndex, path, result):
if currentSum > targetSum: # 剪枝操作
return # 如果path的长度等于k但currentSum不等于targetSum则直接返回
if len(path) == k:
if currentSum == targetSum:
result.append(path[:])
return
for i in range(startIndex, 9 - (k - len(path)) + 2): # 剪枝
currentSum += i # 处理
path.append(i) # 处理
self.backtracking(targetSum, k, currentSum, i + 1, path, result) # 注意i+1调整startIndex
currentSum -= i # 回溯
path.pop() # 回溯
def backtracking(self, k: int, n: int, start_num: int):
if self.sum_now > n: # 剪枝
return
if len(self.path) == k: # len(path)==k时不管sum是否等于n都会返回
if self.sum_now == n:
self.res.append(self.path[:])
return
for i in range(start_num, 10 - (k - len(self.path)) + 1):
self.path.append(i)
self.sum_now += i
self.backtracking(k, n, i + 1)
self.path.pop()
self.sum_now -= i
```
## Go