diff --git "a/problems/0216.\347\273\204\345\220\210\346\200\273\345\222\214III.md" "b/problems/0216.\347\273\204\345\220\210\346\200\273\345\222\214III.md" index fa2ce37f65..76813864b1 100644 --- "a/problems/0216.\347\273\204\345\220\210\346\200\273\345\222\214III.md" +++ "b/problems/0216.\347\273\204\345\220\210\346\200\273\345\222\214III.md" @@ -301,22 +301,29 @@ class Solution { ```py class Solution: - def combinationSum3(self, k: int, n: int) -> List[List[int]]: - res = [] #存放结果集 - path = [] #符合条件的结果 - def findallPath(n,k,sum,startIndex): - if sum > n: return #剪枝操作 - if sum == n and len(path) == k: #如果path.size() == k 但sum != n 直接返回 - return res.append(path[:]) - for i in range(startIndex,9-(k-len(path))+2): #剪枝操作 - path.append(i) - sum += i - findallPath(n,k,sum,i+1) #注意i+1调整startIndex - sum -= i #回溯 - path.pop() #回溯 - - findallPath(n,k,0,1) - return res + def __init__(self): + self.res = [] + self.sum_now = 0 + self.path = [] + + def combinationSum3(self, k: int, n: int) -> [[int]]: + self.backtracking(k, n, 1) + return self.res + + 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 + return ``` ## Go: diff --git "a/problems/\344\272\214\345\217\211\346\240\221\347\220\206\350\256\272\345\237\272\347\241\200.md" "b/problems/\344\272\214\345\217\211\346\240\221\347\220\206\350\256\272\345\237\272\347\241\200.md" index dab434e69c..411e7e22de 100644 --- "a/problems/\344\272\214\345\217\211\346\240\221\347\220\206\350\256\272\345\237\272\347\241\200.md" +++ "b/problems/\344\272\214\345\217\211\346\240\221\347\220\206\350\256\272\345\237\272\347\241\200.md" @@ -227,6 +227,21 @@ function TreeNode(val, left, right) { } ``` +Swift: +```Swift +class TreeNode { + var value: T + var left: TreeNode? + var right: TreeNode? + init(_ value: T, + left: TreeNode? = nil, + right: TreeNode? = nil) { + self.value = value + self.left = left + self.right = right + } +} +``` -----------------------