Feb-06-2022, 12:23 PM
Given an array of integers and a value k, return True if there exists a subset of elements of the array that sums up to k.
This is my algorithm. Initially, the line that I commented was included and the result was that the algorithm outputted True when the answer should have been False. Without the line it seems to work fine. I do not understand why there is a difference in output, can somebody explain?
This is my algorithm. Initially, the line that I commented was included and the result was that the algorithm outputted True when the answer should have been False. Without the line it seems to work fine. I do not understand why there is a difference in output, can somebody explain?
def solve(arr,items,sum,dp): if sum - arr[items] >= 0: dp[items][sum] = max(dp[items-1][sum],dp[items-1][sum-arr[items]]) else: dp[items][sum] = dp[items-1][sum] def driver(arr,k): dp = [[False for j in range(k+1)] for i in range(len(arr))] for i in range(len(arr)): dp[i][0] = True #why does this not work if the line below is executed? #dp[i][arr[i]] = True for i in range(len(arr)): for j in range(k+1): solve(arr,i,j,dp) return dp[len(arr)-1][k]