Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum.
Example:
1. Method 1: Recursion.
Approach: For the recursive approach we will consider two cases.
Following is the recursive formula for isSubsetSum() problem:
isSubsetSum(set, n, sum)
= isSubsetSum(set, n-1, sum) ||
isSubsetSum(set, n-1, sum-set[n-1])
Base Cases:
isSubsetSum(set, n, sum) = false, if sum > 0 and n == 0
isSubsetSum(set, n, sum) = true, if sum == 0
Let’s take a look at the simulation of above approach:
set[] = {3, 4, 5, 2}
sum = 9
(x, y) = 'x' is the left number of elements,
'y' is the required sum
Output: Found a subset with given sum
Complexity Analysis: The above solution may try all subsets of given set in worst case. Therefore time complexity of the above solution is exponential. The problem is in-fact NP-Complete (There is no known polynomial time solution for this problem).
2. Method 2: To solve the problem in Pseudo-polynomial time use the Dynamic programming.
So we will create a 2D array of size (arr.size() + 1) * (target + 1) of type boolean. The state DP[i][j] will be true if there exists a subset of elements from A[0….i] with sum value = ‘j’.
The approach for the problem is:
if (A[i-1] > j)
DP[i][j] = DP[i-1][j]
else
DP[i][j] = DP[i-1][j] OR DP[i-1][j-A[i-1]]
The below simulation will clarify the above approach:
Below is the implementation of the above approach:
Output: Found a subset with given sum
Method:
Below is the implementation of the above approach:
Output: YES
Complexity Analysis
81 videos|80 docs|33 tests
|
|
Explore Courses for Computer Science Engineering (CSE) exam
|