I am working on a code to identify subsets of an array with sum of the elements in subsets equal to a given number, k
. Here is the recursive code I attempted.
First approach:
def subset_sum(arr,curr,k,idx):
if idx==len(arr):
print(curr) //print the current subset for debugging
if sum(curr)==k:
print(curr)
return
subset_sum(arr,curr,k,idx+1) //exclude the element
curr.append(arr[idx]) //include the element
subset_sum(arr,curr,k,idx+1) // make recursive call
Then this function has been called using;subset_sum([1,2,3],[],4,0)
, and we get following output;
[]
[3]
[3]
[3, 2]
[3, 2, 3]
[3, 2, 3, 1]
[3, 2, 3, 1, 3]
[3, 2, 3, 1, 3, 2]
[3, 2, 3, 1, 3, 2, 3]
It is being difficult to comprehend, why are the elements being duplicated above. After some brainstorming, I tried second approach below.
Second approach.
def subset_sum(arr,curr,k,idx):
cnt=0
if idx==len(arr):
if sum(curr)==k:
cnt+=1
print(curr,cnt)
return cnt
subset_sum(arr,curr,k,idx+1)
subset_sum(arr,curr+[arr[idx]],k,idx+1)
We call the function subset_sum([1,2,3],[],3,0,0)
. This gives the output as;
[1,2],1
[3],1
since 1+2 gives us the required sum 3.
May I know what is wrong in updating the element curr
as I did in the first approach; curr.append(arr[idx])
. And why is that the second approach is working fine.