You are on page 1of 2

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING


EXPERIMENT: 2.2
Student Name: Saniya Gupta UID: 21BCS1900
Branch:CSE Section/Group: 613/B
Semester:5th DATE: 21/09/2023
Subject Name: DAA Subject Code: 21CSH-311

Aim: Develop a program and analyze complexity to implement subset-sum problem using
Dynamic Programming.

Objective: Objective is to implement subset-sum problem using Dynamic programming.

Apparatus/Software used: Online GDB

Algorithm:

Step 1: Create a function name isSubsetSum to find the target sum.


Step 2: Create a 2D array and its first column to true.
Step 3: Initialize its first row to false.
Step 4: Start nested for loop to check whether the value of j is greater than orsmaller than set[]
and set the value accordingly.
Step 5: Return subset[n][sum];
Step 6: Enter in main function call the isSubsetSum function.

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]];
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

}
}
return subset[n][sum];
}
int main()
{
int set[] = { 3, 34, 4, 12, 5, 2 };
int n = sizeof(set) / sizeof(set[0]);int
sum;
cout<<"Enter the value of target sum: ";
cin>>sum;
if (isSubsetSum(set, n, sum) == true)cout
<< "Found a target sum";
else
cout << "Target sum is not found";return
0;
}

Output:

Observations/Outcome:
1) I learnt about dynamic programming.
2) I learnt how to check whether target sum is present or not in a set.
3) I learnt about the time complexity of dynamic programming.
Time complexity:
The time complexity of the above program is O(sum*n).

You might also like