$ cat ./coding/216-combination-sum-iii.md
[Coding]
216. Combination Sum III
────────────────────────────────────────────────────────────
這一題和 77. Combinations 與 39. Combination Sum 差不多,其實比 40. Combination II 簡單。
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
ans = []
def backtrack(curr, target, start):
if target == 0 and if len(curr) == k:
ans.append(list(curr))
return
if target < 0:
return
else:
for i in range(start, 10):
curr.append(i)
backtrack(curr, target - i, i + 1)
curr.pop()
backtrack([], n, 1)
return ans
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
res = []
def backtrack(curr, total, start):
if len(curr) == k:
if total == n:
res.append(curr.copy())
return
if total > n:
return
for i in range(start, 10):
curr.append(i)
total += i
backtrack(curr, total, i + 1)
curr.pop()
total -= i
backtrack([], 0, 1)
return res
--tags#Backtrack
$ ls ./coding/ | grep -v 216-combination-sum-iii