|
| 1 | +package com.java.array; |
| 2 | + |
| 3 | +public class FindingAllSubsets { |
| 4 | + |
| 5 | + public static void main(String[] args) { |
| 6 | + //solution 1 follows bitwise approach |
| 7 | +// solution1(); |
| 8 | + |
| 9 | + //solution 2 follows recursion approach |
| 10 | + solution2(); |
| 11 | + } |
| 12 | + |
| 13 | + public static void solution1() { |
| 14 | + char set[] = {'a','b','c','d'}; |
| 15 | + int n = set.length; |
| 16 | + for (int i = 0; i < (1 << n); i++) { |
| 17 | + System.out.print("{ "); |
| 18 | + for (int j = 0; j < n; j++){ |
| 19 | + if ((i & (1 << j)) > 0) |
| 20 | + System.out.print(set[j] + " "); |
| 21 | + } |
| 22 | + System.out.println("}"); |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + public static void solution2(){ |
| 27 | + int array[] = {10,20,30,40,50}; |
| 28 | + int visited[] = new int[array.length]; |
| 29 | + traverse(array, visited,0); |
| 30 | + } |
| 31 | + |
| 32 | + public static void traverse(int array[],int visited[],int curIndex){ |
| 33 | + System.out.print("\n{ "); |
| 34 | + for(int i=0;i<visited.length;i++) |
| 35 | + if(visited[i] == 1) |
| 36 | + System.out.print(array[i]+" "); |
| 37 | + System.out.print("}"); |
| 38 | + |
| 39 | + for(int j=curIndex;j<array.length;j++){ |
| 40 | + visited[j] = 1; |
| 41 | + traverse(array, visited,j+1); |
| 42 | + visited[j] = 0; |
| 43 | + } |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +/* |
| 48 | + * |
| 49 | + * Input: S = {a, b, c, d} Output: {}, {a} , {b}, {c}, {d}, {a,b}, {a,c}, {a,d}, |
| 50 | + * {b,c}, {b,d}, {c,d}, {a,b,c}, {a,b,d}, {a,c,d}, {b,c,d}, {a,b,c,d} |
| 51 | + * |
| 52 | + */ |
0 commit comments