-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSubset.java
More file actions
66 lines (53 loc) · 1.29 KB
/
Subset.java
File metadata and controls
66 lines (53 loc) · 1.29 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
package com.ub.test;
import java.util.ArrayList;
import java.util.List;
public class Subset {
private List<Integer> constructSubset(int x[],int sum) {
List <Integer> y = new ArrayList<Integer>();
int n = x.length;
//base case
if (sum == 0) {
return y;
}else if(sum < 0 || n==0) {
return null;
}else {
int temp[] = new int[n-1];
for(int i=1,j=0;i<n;i++,j++) {
temp[j] = x[i];
}
y = constructSubset(temp, sum); //exclude 1st element
printlist(y);
if(y != null) {
// List<Integer> lst = new ArrayList<Integer>();
// for(int i=0;i<temp.length;i++) {
// lst.add(temp[i]);
// }
// y.addAll(lst);
System.out.println("the size of the list"+y.size());
return y;
}
y = constructSubset(temp, sum-x[0]); //includes 1st element
if(y!= null) {
y.add(x[0]);
printlist(y);
return y;
}
}
return null;
}
private void printlist(List<Integer> y) {
try{
for(int t:y) {
System.out.println(t);
}
}catch (Exception e) {
System.out.println(" 0 elements");
}
}
public static void main(String args[]) {
Subset subset = new Subset();
int x[] = {8,6,7,5,3,10,9};
int sum = 15;
List<Integer> list = subset.constructSubset(x,sum);
}
}