You are on page 1of 3

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

EXPERIMENT: 2.2

Student Name: Vishal Dwivedii UID: 21BCS2844


Branch: CSE Section/Group: 626/B
Semester: 5th
Subject Name: DAA Lab Subject Code: 21CSH-311

1. Aim/Overview of the practical:

To implement subset-sum problem using Dynamic Programming .

2. objective

find whether or not there exists any subset of the given set .

3. Algorithm

i. We create a boolean subset[][] and fill it in bottom up manner.


ii. The value of subset[i][j] will be true if there is a subset of set[0..j-1] with sum

equal to i.,otherwise false.

iii. subset[i][j] = true if there is a subset with:

iv. the i-th element as the last element * sum equal to j

v. subset[i][0] = true as sum of {} = 0 vi. subset[0][j] = false as with no elements we can get
no sum

vii. subset[i][j] = subset[i-1][j-E1]; where E1 = array[i-1] viii. Finally, we returnsubset[n][sum]

4. Steps for experiment/practical/Code:


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

class Solution {
static Boolean isSubsetSum(int N, int arr[], int sum) {
int dp[][] = new int[N][sum+ 1];
for (int row[] : dp)
Arrays.fill(row, -1);
return subsetSumUtil(N - 1, sum, arr, dp);
}
static boolean subsetSumUtil(int ind, int target, int[] arr, int[][] dp) {
if (target == 0)
return true;
if (ind == 0)
return arr[0] == target;
if (dp[ind][target] != -1)
return dp[ind][target] == 0 ? false : true;
boolean notTaken = subsetSumUtil(ind - 1, target, arr, dp);
boolean taken = false;
if (arr[ind] <= target)
taken = subsetSumUtil(ind - 1, target - arr[ind], arr, dp);
dp[ind][target] = notTaken || taken ? 1 : 0;
return notTaken || taken;
}
}

output
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

4. Observations/Discussions/ Complexity Analysis:

• Worst case time complexity: Θ(n*sum)

• Space complexity: Θ(sum)

Learning Outcomes:-

1. Create a program keeping in mind the time complexity

2. Create a program keeping in mind the space complexity

3. Steps to make optimal algorithm

4. Learnt about how to implement subset sum problem using dynamic programming.

You might also like