|
| 1 | +/* |
| 2 | +Given an integer array (of length n), find and print all the subsets of input array. |
| 3 | +Subsets are of length varying from 0 to n, that contain elements of the array. But the order of elements should remain same as in the input array. |
| 4 | +Note : The order of subsets are not important. Just print the subsets in different lines. |
| 5 | + |
| 6 | +Input format : |
| 7 | +Line 1 : Integer n, Size of array |
| 8 | +Line 2 : Array elements (separated by space) |
| 9 | + |
| 10 | +Constraints : |
| 11 | +1 <= n <= 15 |
| 12 | + |
| 13 | +Sample Input: |
| 14 | +3 |
| 15 | +15 20 12 |
| 16 | +Sample Output: |
| 17 | +[] (this just represents an empty array, don't worry about the square brackets) |
| 18 | +12 |
| 19 | +20 |
| 20 | +20 12 |
| 21 | +15 |
| 22 | +15 12 |
| 23 | +15 20 |
| 24 | +15 20 12 |
| 25 | +*/ |
| 26 | +public class solution { |
| 27 | + public static void printSubsets(int input[]) { |
| 28 | + // Write your code here |
| 29 | + printSubsetsHelper(input,0,new int[0]); |
| 30 | + } |
| 31 | + |
| 32 | + private static void printSubsetsHelper(int[] input, int startIndex, int[] output) |
| 33 | + { |
| 34 | + //Base case - If start index = input.length, print the output and return |
| 35 | + if (startIndex==input.length) |
| 36 | + { |
| 37 | + for (int i=0;i<output.length;i++) |
| 38 | + { |
| 39 | + System.out.print(output[i]+" "); |
| 40 | + } |
| 41 | + System.out.println(); |
| 42 | + return; |
| 43 | + } |
| 44 | + |
| 45 | + //Case one, output contains element of input array at startIndex |
| 46 | + int[] newOutput = new int[output.length+1]; |
| 47 | + for (int i=0;i<output.length;i++) |
| 48 | + { |
| 49 | + newOutput[i]=output[i]; |
| 50 | + } |
| 51 | + newOutput[output.length]=input[startIndex]; |
| 52 | + printSubsetsHelper(input,startIndex+1,newOutput); |
| 53 | + |
| 54 | + //Case 2, output does not contain element of input array at startIndex |
| 55 | + printSubsetsHelper(input,startIndex+1,output); |
| 56 | + } |
| 57 | +} |
0 commit comments