Experiment No. 2.
Student Name: Avinash Mathur UID: 21BCS11075
Branch: CSE Section/Group: 21BCS-SN-901/B
Semester: 5th Date of Performance: 29/09/2023
Subject Name: DAA Lab Subject Code: 21CSH-311
Aim: Develop a program and analyze complexity to implement subset-sum problem using
Dynamic Programming
Objective: To demonstrate 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
• The time complexity of this code is O(sum*n)
• The space complexity is also O(n*sum)
Learning Outcomes:
• Understanding Dynamic Programming.
• understand how to work with 2D arrays.
• Understand about the Subset Sum Problem.
• Understand how Boolean data types are used