Combination Sum III (Leetcode 216)

Problem Link: https://leetcode.com/problems/combination-sum-iii/

class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        
        ans=[]
        def recursion(i,target,k,tempSum,tempArr):
             
            # Always Remember!
            
            # The base case which brings us answer must be
            # above of all other base cases in any recursion.
            if(len(tempArr)==k):
                if(tempSum==target):
                    ans.append(tempArr)     
                return
            
            if(i>=10):
                return
            
            ele=i
            temp=tempArr[:]
            temp.append(ele)
            
            # Considering the element
            recursion(i+1,target,k,tempSum+ele,temp)
            
            #Ignoring the element
            recursion(i+1,target,k,tempSum,tempArr)
            
        
        recursion(1,n,k,0,[])
        return ans

Last updated