|
| 1 | +import java.io.*; |
| 2 | +import java.util.*; |
| 3 | + |
| 4 | +class sumofsubset |
| 5 | +{ |
| 6 | + // Return true if there exists a sub-array of array[0..n] with given sum |
| 7 | + public static boolean subsetSum(int[] A, int n, int sum) |
| 8 | + { |
| 9 | + // return true if sum becomes 0 (subset found) |
| 10 | + if (sum == 0) { |
| 11 | + return true; |
| 12 | + } |
| 13 | + |
| 14 | + // base case: no items left or sum becomes negative |
| 15 | + if (n < 0 || sum < 0) { |
| 16 | + return false; |
| 17 | + } |
| 18 | + |
| 19 | + // Case 1. include current item in the subset (A[n]) and recur |
| 20 | + // for remaining items (n - 1) with remaining sum (sum - A[n]) |
| 21 | + boolean include = subsetSum(A, n - 1, sum - A[n]); |
| 22 | + |
| 23 | + // Case 2. exclude current item n from subset and recur for |
| 24 | + // remaining items (n - 1) |
| 25 | + boolean exclude = subsetSum(A, n - 1, sum); |
| 26 | + |
| 27 | + // return true if we can get subset by including or excluding the |
| 28 | + // current item |
| 29 | + return include || exclude; |
| 30 | + } |
| 31 | + |
| 32 | + // Subset Sum Problem |
| 33 | + public static void main(String[] args) |
| 34 | + { |
| 35 | + // Input: set of items and a sum |
| 36 | + Scanner a = new Scanner(System.in); |
| 37 | + int n = a.nextInt(); |
| 38 | + int sum = a.nextInt(); |
| 39 | + int[] A = new int[n]; |
| 40 | + for(int i=0;i<n;i++) |
| 41 | + A=a.nextInt(); |
| 42 | + |
| 43 | + if (subsetSum(A, A.length - 1, sum)) { |
| 44 | + System.out.print("Yes"); |
| 45 | + } |
| 46 | + else { |
| 47 | + System.out.print("No"); |
| 48 | + } |
| 49 | + } |
| 50 | +} |
0 commit comments