-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSub_Set.java
More file actions
90 lines (83 loc) · 1.95 KB
/
Sub_Set.java
File metadata and controls
90 lines (83 loc) · 1.95 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
Design and implement in Java to find a subset of a given set S = {Sl, S2,.....,Sn} of n
positive integers whose SUM is equal to a given positive integer d. For example, if S ={1, 2, 5,
6, 8} and d= 9, there are two solutions {1,2,6}and {1,8}. Display a suitable message, if the
given problem instance doesn't have a solution.
*/
import java.util.Scanner;
public class Sub_Set
{
static int set[]=new int[10];
static int solvector[]=new int [10];
static int target;
static int count=0;
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of items: ");
int no_ele= sc.nextInt();
System.out.println("Enter the numbers in ascending order");
for(int i=0; i<no_ele;i++)
set[i]=sc.nextInt();
System.out.println("Enter the target sum");
target=sc.nextInt();
int tot_sum=0;
for(int i=0;i<no_ele;i++)
{
tot_sum=tot_sum+set[i];
}
if(target>tot_sum)
{
System.out.println("Solution doesnt Exist");
System.exit(0);
}
System.out.println("The solutions are");
Subset(0,0,tot_sum);
}
public static void Subset(int sumsofar, int index,int remsum)
{
solvector[index]=1;
if(sumsofar+set[index]==target)
{
System.out.println("Solution No: = "+ (++count));
for(int i=0;i<=index;i++)
{
if(solvector[i]==1)
System.out.println(" "+set[i]);
}
}
else if(sumsofar+set[index]+set[index+1]<=target)
{
Subset(sumsofar+set[index], index+1, remsum-set[index]);
}
if((sumsofar+remsum-set[index]>=target)&& (sumsofar+set[index+1]<=target))
{
solvector[index]=0;
Subset(sumsofar,index+1,remsum-set[index]);
}
}
}
/*
OUTPUT
Enter the number of items:
6
Enter the numbers in ascending order
1
3
5
7
9
11
Enter the target sum
12
the solution vector is
Solution No: = 1
1
11
Solution No: = 2
3
9
Solution No: = 3
5
7
*/