Leetcode 216 Combination Sum III

https://leetcode.cn/problems/combination-sum-iii/

 

递归标准题目

 

先写递归函数,一边写一边看缺少什么输入。

因为数字不能重复,而且从小到大排序正好能去重,因此对当前剩下的list而言,遍历时给到下一层递归的只能是右侧的数组。

比如list=[4,5,6,7,8,9],本次循环了4,再循环到5,那么塞给下一层的可选择范围就是list=[6,7,8,9]。基本上就这一个地方需要注意了。

class Solution:
    ans=[]
    def recur(self,k,n,st,cur):
        if k==1 and n in st: # 优化提前终止
            self.ans.append(cur+[n])
        if k==1 and n not in st:
            return
        if n<0 or k>len(st): # 优化提前终止
            return
        for i in range(len(st)):
            cur+=[st[i]]
            self.recur(k-1,n-st[i],st[i+1:],cur)
            cur.pop()


    def combinationSum3(self, k: int, n: int) -> list[list[int]]:
        self.ans=[]
        st=list(range(1,10))
        cur=[]
        self.recur(k,n,st,cur)
        return self.ans

 

posted @ 2022-05-10 19:02  Cloud.9  阅读(17)  评论(1编辑  收藏  举报