Avinash DAA 2.2
Avinash DAA 2.2
Aim: Develop a program and analyze complexity to implement subset-sum problem using
Dynamic Programming
Algorithm
• Step 1: Create a 2D array subset[][] of size (n+1) x (sum+1).
• Step 2: Fill the first column with true (as 0 sum can always be achieved).
• Step 3: Fill the first row, except subset[0][0], with false (as non-zero sum cannot be
achieved with 0 elements).
• Step 4: For each subset, if sum can be obtained either by including or excluding the current
element, mark it as true.
• Step 5: Return subset[n][sum], which indicates if sum can be achieved with all elements.
Source Code:
#include<bits/stdc++.h>
using namespace std;
bool isSubsetSum(int set[], int n, int sum) {
bool subset[n+1][sum+1];
for (int i = 0; i <= n; i++)
subset[i][0] = true;
for (int i = 1; i <= sum; i++)
subset[0][i] = false;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= sum; j++) {
if(j<set[i-1])
subset[i][j] = subset[i-1][j];
if (j >= set[i-1])
subset[i][j] = subset[i-1][j] || subset[i - 1][j-set[i-1]];
}
}
return subset[n][sum];
}
int main() {
cout<<"Avinash Mathur UID: 21BCS11075"<<endl;
int n, sum;
cout << "Enter the number of elements in the set: ";
cin >> n;
int set[n];
cout << "Enter the elements of the set: ";
for(int i = 0; i < n; i++)
cin >> set[i];
cout << "Enter the sum: ";
cin >> sum;
if (isSubsetSum(set, n, sum) == true)
cout << "Found a subset with given sum";
else
cout << "No subset with given sum";
return 0;
}
Output:
Time and Space Complexity
Learning Outcomes: