Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit eaf8e4c

Browse files
Create Return subset of an array
1 parent 77b7eea commit eaf8e4c

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/*
2+
Given an integer array (of length n), find and return 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.
5+
Input format :
6+
Line 1 : Size of array
7+
Line 2 : Array elements (separated by space)
8+
9+
Sample Input:
10+
3
11+
15 20 12
12+
Sample Output:
13+
[] (this just represents an empty array, don't worry about the square brackets)
14+
12
15+
20
16+
20 12
17+
15
18+
15 12
19+
15 20
20+
15 20 12
21+
*/
22+
23+
public class solution {
24+
25+
// Return a 2D array that contains all the subsets
26+
public static int[][] subsets(int input[]) {
27+
// Write your code here
28+
return subsetsHelper(input,0);
29+
}
30+
31+
private static int[][] subsetsHelper(int[] input, int startIndex)
32+
{
33+
if (startIndex==input.length)
34+
{
35+
return new int[1][0];
36+
}
37+
int[][] temp = subsetsHelper(input, startIndex+1);
38+
//System.out.println("Length of 2D matrix: "+temp.length);
39+
int[][] smallOutput = new int[temp.length*2][];
40+
41+
for (int i=0;i<temp.length;i++)
42+
{
43+
smallOutput[i] = new int[temp[i].length];
44+
int[] smallTemp = temp[i];
45+
for (int j=0;j<temp[i].length;j++)
46+
{
47+
smallOutput[i][j]=smallTemp[j];
48+
}
49+
}
50+
51+
for (int i=0;i<temp.length;i++)
52+
{
53+
smallOutput[i+temp.length] = new int[temp[i].length+1];
54+
smallOutput[i+temp.length][0]=input[startIndex];
55+
int[] smallTemp = temp[i];
56+
for (int j=1;j<=temp[i].length;j++)
57+
{
58+
smallOutput[i+temp.length][j]=smallTemp[j-1];
59+
}
60+
}
61+
/*
62+
for (int i=0;i<smallOutput.length;i++)
63+
{
64+
int[] temp1 = smallOutput[i];
65+
for (int j=0;j<temp1.length;j++)
66+
{
67+
System.out.print(temp1[j]+" ");
68+
}
69+
System.out.println();
70+
}
71+
System.out.println();
72+
*/
73+
return smallOutput;
74+
}
75+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /