python dfs solution


  • 0
    G
    class Solution(object):
        def dfs(self,res,tmp,nums,n,k,idx):
            if n==0 and len(tmp)==k:
                res.append(tmp[:])
            if n<=0 or len(tmp)>=k:
                return
            for i in range(idx,9):
                self.dfs(res,tmp+[nums[i]],nums,n-nums[i],k,i+1)
            
        def combinationSum3(self, k, n):
            """
            :type k: int
            :type n: int
            :rtype: List[List[int]]
            """
            res=[]
            nums=[1,2,3,4,5,6,7,8,9]
            self.dfs(res,[],nums,n,k,0)
            return res
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.