K Sum

Question (LI.89)

Brute Force Code

Search problem at the first glance

def kSum(
    self, 
    arr: List[int], 
    size: int, 
    target_sum: int
) -> int:
    return self.countHelper(arr, 0, size, target_sum) 
    
def countHelper(
    self, 
    arr: List[int], 
    start: int, 
    size: int, 
    target_sum: int
) -> int:
        
        # print(f'{start}-{size}-{target_sum}')
        # print(f'current item {arr[start]}')
        count = 0
        
        # base 
        
        if size < 0: 
            return 0
        
        if size == 0:
            if target_sum > 0:
                # print("end of branch")
                return 0
            if target_sum == 0:
                # print("working solution")
                return 1        
        
        # recursion 
        
        if start < len(arr):
            
            for i in range(start, len(arr)):
            
                count += self.countHelper(
                    arr, i + 1, size - 1, target_sum - arr[i]
                )
            
        # return  
        
        return count

Memoized Code

Python has issues with initializing a multi-dimensional array

Analysis

K Sum is a 0/1 knapsack because we want subsets. It has one more constraint. That's all.

Last updated