forked from auralshin/competetive-code-hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRecursion
More file actions
66 lines (54 loc) · 1.59 KB
/
Copy pathRecursion
File metadata and controls
66 lines (54 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
Return Subsets of an array
Given an integer array (of length n), find and return all the subsets of input array.
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.
Note : The order of subsets are not important.
Input format :
Line 1 : Size of array
Line 2 : Array elements (separated by space)
Sample Input:
3
15 20 12
Sample Output:
[] (this just represents an empty array, don't worry about the square brackets)
12
20
20 12
15
15 12
15 20
15 20 12
Below is the implementation of above approach
public class solution {
public static int[][] subsets(int input[]) {
return subsets(input,0);
}
public static int[][] subsets(int input[],int firstindex)
{
if(input.length==firstindex)
{
int subset[][]= {{}};
return subset;
}
int smallans[][]= subsets(input,firstindex+1);
int ans[][] = new int[smallans.length*2][];
int k=0;
for(int x=0;x<smallans.length;x++)
{
ans[x]= new int[smallans[x].length];
for(int y=0;y<smallans[x].length;y++)
ans[x][y]= smallans[x][y];
k++;
}
for(int x=0;x<smallans.length;x++)
{
ans[k]= new int[smallans[x].length+1];
ans[k][0]=input[firstindex];
for(int y=0;y<smallans[x].length;y++)
{
ans[k][y+1]=smallans[x][y];
}
k++;
}
return ans;
}
}