From f74f78df436ce95059c0c70e03e1bf601d1ecf6b Mon Sep 17 00:00:00 2001 From: Akash Upadhyay <62694340+Spectre-ak@users.noreply.github.com> Date: Mon, 15 Feb 2021 13:24:46 +0530 Subject: [PATCH] Added print the subset function. Added the support for printing the subset with the given sum in SubsetSum.java --- src/com/interview/dynamic/SubsetSum.java | 27 ++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/com/interview/dynamic/SubsetSum.java b/src/com/interview/dynamic/SubsetSum.java index e9f9b6a9..6b6b7e2a 100644 --- a/src/com/interview/dynamic/SubsetSum.java +++ b/src/com/interview/dynamic/SubsetSum.java @@ -61,6 +61,33 @@ public boolean partition(int arr[]) { } return T[arr.length][sum]; } + public static void printTheSubset(boolean dp[][], int arr[],int total) { + List ansIntegers = new ArrayList<>(); + int x = arr.length, y = total; + if (dp[x][y]) + while (x != 0 || y != 0) { + if (x == 0 & y != 0) { + ansIntegers.add(arr[x-1]); + break; + } + if (x != 0 && y == 0) { + if (dp[x][y] == dp[x - 1][y]) { + x = x - 1; + } + continue; + } + if (dp[x][y] == dp[x - 1][y]) { + x = x - 1; + + } else { + ansIntegers.add(arr[x-1]); + y = y - arr[x-1]; + x = x - 1; + } + } + + System.out.println(ansIntegers); + } public static void main(String args[]) { SubsetSum ss = new SubsetSum();