From 82a562a6d4cfd65eb969eee96a17c56a86bbbb3b Mon Sep 17 00:00:00 2001 From: Shubham-Singh-Rajput <88304238+shubham-singh-748@users.noreply.github.com> Date: Sat, 9 Oct 2021 14:27:20 +0530 Subject: [PATCH] Add sum of subset problem using DP (#2451) --- DynamicProgramming/Sum_Of_Subset.java | 28 +++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 DynamicProgramming/Sum_Of_Subset.java diff --git a/DynamicProgramming/Sum_Of_Subset.java b/DynamicProgramming/Sum_Of_Subset.java new file mode 100644 index 000000000..a1dc24b34 --- /dev/null +++ b/DynamicProgramming/Sum_Of_Subset.java @@ -0,0 +1,28 @@ +public class Sum_Of_Subset { + public static void main(String[] args){ + + int[] arr = { 7, 3, 2, 5, 8 }; + int Key = 14; + + if (subsetSum(arr, arr.length - 1, Key)) { + System.out.print("Yes, that sum exists"); + } + else { + System.out.print("Nope, that number does not exist"); + } + } + public static boolean subsetSum(int[] arr, int num, int Key) + { + if (Key == 0) { + return true; + } + if (num < 0 || Key < 0) { + return false; + } + + boolean include = subsetSum(arr, num - 1, Key - arr[num]); + boolean exclude = subsetSum(arr, num - 1, Key); + + return include || exclude; + } +}