-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSubset.java
More file actions
54 lines (45 loc) · 1.3 KB
/
Copy pathSubset.java
File metadata and controls
54 lines (45 loc) · 1.3 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
package com.programs;
import java.util.Scanner;
public class Subset {
private static int d,count=0,x[] = new int[20],w[] = new int[20];
public static void main(String[] args) {
int i,n,sum=0;
System.out.println("Enter the no. of elements:");
Scanner in = new Scanner(System.in);
n = in.nextInt();
System.out.println("Enter the elements in ascending order:");
for(i=0;i<n;i++)
w[i] = in.nextInt();
System.out.println("Enter the required sum:");
d = in.nextInt();
for(i=0;i<n;i++)
sum+=w[i];
if(sum<d)
{
System.out.println("There is no solution");
return;
}
subset(0,0,sum);
if(count==0) {
System.out.println("No solution");
return;
}
}
public static void subset(int cs,int k,int r) {
int i;
x[k] = 1;
if(cs+w[k]==d) {
System.out.println("Subset "+(++count));
for(i=0;i<=k;i++)
if(x[i]==1)
System.out.println(w[i]);
}
else if(cs+w[k]+w[k+1]<=d) {
subset((cs+w[k]),k+1,r-w[k]);
}
if(cs+r-w[k]>=d && cs+w[k]<=d) {
x[k] = 0;
subset(cs, k + 1, r - w[k]);
}
}
}