LIFE_GOES_ON's blog

By LIFE_GOES_ON, history, 4 years ago, In English

My observation is : Let an array A has length n and a subset of A is B. Now, if B has length k then it appears also in other 2^(n-k) subsets of array A.

So I used a 2d dp dp[i][j] which denotes if I take elements upto i then how many subsets have remaining sum j. And the ans is dp[n][0].

Base case is when i >= n then if the remaining sum is 0 that means we got a subset having sum S. Now we have to return in how many other subsets the current segment belongs. So if remaining sum = 0 then I returned pow(2,n-k) otherwise 0;

I thought this is the correct approach. Please correct my approach. I don't understand why it is not working.

Problem Link

My Code
  • Vote: I like it
  • 0
  • Vote: I do not like it

| Write comment?
»
8 months ago, # |
  Vote: I like it 0 Vote: I do not like it

I think you will have to introduce another state in your dp to get the correct solution but it would be too slow then , you can define your dp ij as till prefix i , what is the sum of count of subsequences such that their sum is j and then the transitions are straightforward.

Solution:You can refer my submission here to get a hint