Skip to content

Commit a506bb5

Browse files
authored
Create Print subsets sum to K
1 parent d4681f8 commit a506bb5

File tree

1 file changed

+86
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)