Skip to content

Commit 77b7eea

Browse files
authored
Create Return subsets sum to K
1 parent fd88f19 commit 77b7eea

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
/*
2+
Given an array A of size n and an integer K, return all subsets of A which sum to K.
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+
6+
Input format :
7+
Line 1 : Integer n, Size of input array
8+
Line 2 : Array elements separated by space
9+
Line 3 : K
10+
11+
Constraints :
12+
1 <= n <= 20
13+
14+
Sample Input :
15+
9
16+
5 12 3 17 1 18 15 3 17
17+
6
18+
Sample Output :
19+
3 3
20+
5 1
21+
*/
22+
23+
24+
public class solution {
25+
26+
// Return a 2D array that contains all the subsets which sum to k
27+
public static int[][] subsetsSumK(int input[], int k) {
28+
// Write your code here
29+
return subsetsSumKHelper(input,k,0);
30+
}
31+
32+
private static int[][] subsetsSumKHelper(int input[], int k, int startIndex)
33+
{
34+
//Base case - If startIndex == input.length
35+
//We can have two cases in the base condition
36+
//1. If k==0 - This means the desired sum has been achieved by including the last element of the input array
37+
//2. If k!=0 - Desired sum has not been achieved even when last element is included
38+
if (startIndex==input.length)
39+
{
40+
int arr[][];
41+
if (k==0)
42+
{
43+
arr = new int[1][0];
44+
}
45+
else
46+
{
47+
arr = new int[0][0];
48+
}
49+
return arr;
50+
}
51+
52+
//Considering recursive hypothesis where we have the subsets of two cases
53+
//1. Subsets containing current input[startIndex] element - temp1
54+
//2. Subsets not containing current input[startIndex] element - temp2
55+
int temp1[][] = subsetsSumKHelper(input,k-input[startIndex],startIndex+1);
56+
int temp2[][] = subsetsSumKHelper(input,k,startIndex+1);
57+
58+
//Now, we simply need to combine temp1 and temp2 and return to the calling function
59+
//When copying temp1 into output, we need to ensure we also include current input[startIndex] as the first element of that row
60+
int output[][] = new int[temp1.length+temp2.length][];
61+
for (int i=0;i<temp2.length;i++)
62+
{
63+
output[i] = new int[temp2[i].length];
64+
for (int j=0;j<temp2[i].length;j++)
65+
{
66+
output[i][j]=temp2[i][j];
67+
}
68+
}
69+
70+
for (int i=0;i<temp1.length;i++)
71+
{
72+
output[i+temp2.length] = new int[temp1[i].length+1];
73+
output[i+temp2.length][0] = input[startIndex];
74+
for (int j=1;j<output[i+temp2.length].length;j++)
75+
{
76+
output[i+temp2.length][j]=temp1[i][j-1];
77+
}
78+
}
79+
80+
return output;
81+
}
82+
}

0 commit comments

Comments
 (0)