216.组合总和III
题目链接/文章讲解:代码随想录
视频讲解:和组合问题有啥区别?回溯算法如何剪枝?| LeetCode:216.组合总和III_哔哩哔哩_bilibili
跟77题差不多,要搞清楚k确定了递归的深度
依旧用回溯三部曲,就是终止条件多了
class Solution:def combinationSum3(self, k: int, n: int) -> List[List[int]]:result = []self.backtracking(n,k,1,[],result)return resultdef backtracking(self,n,k,startIndex,path,result):if len(path) == k and sum(path) == n:result.append(path[:])for i in range(startIndex,10): path.append(i)self.backtracking(n,k,i+1,path,result)path.pop()
剪枝优化
class Solution:def combinationSum3(self, k: int, n: int) -> List[List[int]]:result = []self.backtracking(n,k,1,[],result)return resultdef backtracking(self,n,k,startIndex,path,result):if sum(path)>n: #优化,当sum(path)>n的时候,就不往下递归了returnif len(path) == k and sum(path) == n:result.append(path[:])for i in range(startIndex,9-(k-len(path))+2): #优化path.append(i)self.backtracking(n,k,i+1,path,result)path.pop()