题目
'''
Description: 216.组合总和III
Autor: 365JHWZGo
Date: 2021-12-27 12:05:10
LastEditors: 365JHWZGo
LastEditTime: 2021-12-27 12:56:21
'''
思路
这道题和昨天唯一的区别在于不光是要由k个数组成,而且这k个数的和还得=n才能加入到结果集中,所以在结束条件时需要多加一个条件。
另一点就是组成的temp的值都得在【0,9】之间,意味着当大于9时,就结束循环。
还有一个判断条件时,当不到len(temp)<=k时,如果sum(temp)+i就已经大于n了,就直接结束循环。
代码
class Solution(object):
def combinationSum3(self, k, n):
"""
:type k: int
:type n: int
:rtype: List[List[int]]
"""
res = []
temp = []
def backtracking(k, n, startIndex):
if k == len(temp):
if sum(temp) == n:
res.append(temp+[])
return
for i in range(startIndex, n-sum(temp)+1 if n-sum(temp)+1<=10 else 10):
if sum(temp)+i <= n:
temp.append(i)
backtracking(k, n, i+1)
temp.pop()
backtracking(k, n, 1)
return res
运行结果
总结
这题难度不大,通过昨天的理解后,今天明显做起题来游刃有余,希望自己再接再厉!