Given an array of size n and a sum K, determine whether any subset is possible with that sum or not. Print \"yes\" if there is any subset present else print \"no\"
All Answers
total answers (1)
Severity: 8192
Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated
Filename: libraries/Filtered_db.php
Line Number: 23
total answers (1)
Of course the naïve solution would be to generate all possible subsets and check their sum equals to K or not. But it would of course be computationally exponential to generate all possible subsets.
To do so, the recursion would be:
For nth element the cases are:
So, the recursion function can be written as:
Where,
Now base case would be,
Here comes the concept of sub problem. Initially the problem is for size n and sum K. Then it gets reduced to {size (n-1) and sum K} or {size (n-1) and (sum K-arr[n-1])}
So if you draw the recursion tree there will be many such sub-problem which will be overlapping ones. That means we will re-compute same sub-problems again and again. That’s why we need to store the value of sub-problems and use dynamic programming.
Converting to dynamic programming:
C++ Implementation:
Output