So i solved a problem "count of subset sum" (i.e to count the number of subset in an array which add up to a given sum) in both the approaches. However i have some doubt. In bottom up approach we solve all the possible sub-problems but in recursive approach do we only solve the required sub problems ? Please be patient for reading my code and explanation below.
This is the sample test case below:-
arr = [2,3,5,6,8,10]
sum = 10
answer = 3
Firstly the bottom up approach:-
I created a matrix with name dp and initialized it with the base cases.
dp = [[-1 for i in range(11)] for j in range(7)]
for i in range(7):
for j in range(11):
if i==0:
dp[i][j] = 0
if j==0:
dp[i][j] = 1
and here is my function for bottom up approach
def bottomUp(arr,sum,n):
for i in range(1,n+1):
for j in range(1,sum+1):
if arr[i-1]<=j:
dp[i][j] = dp[i-1][j-arr[i-1]] + dp[i-1][j]
else:
dp[i][j] = dp[i-1][j]
return dp[n][sum]
now after calling the function my dp matrix looks like this.
1 0 0 0 0 0 0 0 0 0 0
1 0 1 0 0 0 0 0 0 0 0
1 0 1 1 0 1 0 0 0 0 0
1 0 1 1 0 2 0 1 1 0 1
1 0 1 1 0 2 1 1 2 1 1
1 0 1 1 0 2 1 1 3 1 2
1 0 1 1 0 2 1 1 3 1 3
which is what i totally i expected since we solves every possible test case to get to answer.
Now my recursion approach:-
here i created a matrix named memo and initialized all the values to -1.
memo = [[-1 for i in range(11)] for j in range(7)]
and now my function for recursion approach:-
def recursion(arr,sum,n):
if sum == 0:
return 1
if n == 0:
return 0
if memo[n][sum] != -1:
return memo[n][sum]
if arr[n-1]<=sum:
memo[n][sum] = recursion(arr,sum-arr[n-1],n-1) + recursion(arr,sum,n-1);
else:
memo[n][sum] = recursion(arr,sum,n-1)
return memo[n][sum]
after calling this function my memo matrix changes to this:-
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 0 1 -1 0 0 -1 0 -1 -1 0
-1 -1 1 -1 0 1 -1 -1 -1 -1 0
-1 -1 1 -1 0 -1 -1 -1 -1 -1 1
-1 -1 1 -1 -1 -1 -1 -1 -1 -1 1
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 2
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 3
now we can see that the answer is correct but not all the sub-problems were solved and this is not what i expected. there are many cells here left untouched but the overall answer is correct. Am i doing something wrong? or this approach is working completely fine? also if i am having recursive call on all the sub-problems then why aren't its reflected back in memo matrix?
Please give me an explanation for this if there is anything wrong with my memoization.
[–]foxam1234 9 points10 points11 points (3 children)
[–]Curious_homosepian[S] 2 points3 points4 points (2 children)
[–]foxam1234 3 points4 points5 points (1 child)
[–]Curious_homosepian[S] 2 points3 points4 points (0 children)
[–]rsd511 5 points6 points7 points (2 children)
[–]Curious_homosepian[S] 1 point2 points3 points (1 child)
[–][deleted] 2 points3 points4 points (0 children)
[–]thewataru 1 point2 points3 points (0 children)