-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArraySumPossible.java
More file actions
83 lines (70 loc) · 2.19 KB
/
Copy pathArraySumPossible.java
File metadata and controls
83 lines (70 loc) · 2.19 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
package DynamicProgramming;
import java.util.HashMap;
public class ArraySumPossible {
public static void main(String[] args) {
int[] num = { 1, 2, 3 };
int amount = 4;
System.out.println("All possible sum: " + sumAllPossible(amount, new HashMap<>(), num, ""));
System.out.println("Is Possible sum: " + isSumPossible(amount, new HashMap<>(), num));
System.out.println("The minimal possible: "+MinPossibleLength(amount, new HashMap<>(), num, ""));
}
public static boolean sumAllPossible(int amount, HashMap<Integer, Boolean> mem, int[] num, String path) {
if (amount == 0) {
System.out.println(path);
return true;
}
if (mem.containsKey(amount)) {
System.out.println(path);
return mem.get(amount);
}
boolean res = false;
for (int i = 0; i < num.length; i++) {
if (num[i] <= amount) {
int subAmount = amount - num[i];
boolean r = sumAllPossible(subAmount, mem, num, path + Integer.toString(num[i]));
mem.put(subAmount, r);
res = r || res;
}
}
return res;
}
public static boolean isSumPossible(int amount, HashMap<Integer, Boolean> mem, int[] num) {
if (amount == 0)
return true;
if (amount < 0) {
return false;
}
if (mem.containsKey(amount)) {
return mem.get(amount);
}
for (int i = 0; i < num.length; i++) {
int subAmount = amount - num[i];
if (isSumPossible(subAmount, mem, num)) {
mem.put(subAmount, true);
return true;
}
}
mem.put(amount, false);
return false;
}
public static int MinPossibleLength(int amount, HashMap<Integer, Boolean> mem, int[] num, String path) {
if (amount == 0) {
System.out.println(path);
return path.length();
}
// if (mem.containsKey(amount)) {
// System.out.println(path);
// return mem.get(amount);
// }
int res = -1;
for (int i = 0; i < num.length; i++) {
if (num[i] <= amount) {
int subAmount = amount - num[i];
int r = MinPossibleLength(subAmount, mem, num, path + Integer.toString(num[i]));
// mem.put(subAmount, r);
res = res == -1 ? r : res < r ? res : r;
}
}
return res;
}
}