Repository navigation
Expand file tree
/
Copy pathSubsetSum.java
More file actions
81 lines (71 loc) · 2.36 KB
/
Copy pathSubsetSum.java
File metadata and controls
81 lines (71 loc) · 2.36 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
import java.util.*;
/*
* The algorithm determines if it is possible to obtain a sum equivalent to a given number in any subset of the vector limited by a given index
*
* Example:
* vector = [12, 35, 3, 62, 5, 100, 76]
* limitIndex = 4 (then the query will only consider [12, 35, 3, 62, 5])
* target = 20
* answer: True, 12 + 3 + 5 = 20
*
* @problem: https://www.geeksforgeeks.org/subset-sum-problem-dp-25/
* @author Alisson Diego D.
*/
public class SubsetSum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements of the vector: ");
int vectLength = sc.nextInt();
int[] vect = new int[vectLength];
System.out.println("Enter the elements of the vector: ");
for(int i=0; i<vectLength; i++) {
vect[i] = sc.nextInt();
}
String newQuery;
do{
System.out.printf("Enter the limit index of the query (max %d): ", vectLength-1);
int limitIndex = sc.nextInt();
System.out.print("Enter the target sum: ");
int target = sc.nextInt();
if(target == 0) {
System.out.println("It is possible to sum 0 choosing an empty subset of the vector");
}
else {
String result = possibleSum(limitIndex, target, vect);
if( result != null) {
System.out.printf("It is possible to sum %d with %s\n", target, result);
}
else {
System.out.printf("It is not possible to sum %d\n", target);
}
}
sc.nextLine();
System.out.println("New query (s/n)? ");
newQuery = sc.nextLine();
}while(!newQuery.toLowerCase().matches("n"));
sc.close();
}
public static String possibleSum(int limitIndex, int target, int[] vect) {
Map<Integer, String> sums = new HashMap<>(); // HashMap that will contain possible sums of subsets of the list
sums.put(0, "0");
sums.put(vect[0], String.format("%d", vect[0]));
if(sums.containsKey(target)) {
return sums.get(target);
}
for (int i=1; i <= limitIndex; i++) {
List<Integer> keys = new ArrayList<Integer>(sums.keySet()); // Array with the keys of the Hashmap "sums"
for (int key: keys) {
int newSum = key + vect[i];
if(newSum <= target) {
if(!sums.containsKey(newSum)) {
sums.put(newSum, sums.get(key) + " + " + vect[i]);
}
if(newSum == target) {
return sums.get(target);
}
}
}
}
return null;
}
}