FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
Java/DynamicProgramming/KnapsackMemoization.java at master · kaishui/Java · GitHub
kaishui
/
Java
Public
forked from
TheAlgorithms/Java
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
Java
/
DynamicProgramming
/
KnapsackMemoization.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
53 lines (46 loc) · 1.53 KB
Breadcrumbs
Java
/
DynamicProgramming
/
KnapsackMemoization.java
Copy path
File metadata and controls
53 lines (46 loc) · 1.53 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
package
DynamicProgramming
;
import
java
.
util
.
Arrays
;
/**
* Recursive Solution for 0-1 knapsack with memoization
*/
public
class
KnapsackMemoization
{
private
static
int
[][]
t
;
// Returns the maximum value that can
// be put in a knapsack of capacity W
public
static
int
knapsack
(
int
[]
wt
,
int
[]
value
,
int
W
,
int
n
) {
if
(
t
[
n
][
W
] != -
1
) {
return
t
[
n
][
W
];
}
if
(
n
==
0
||
W
==
0
) {
return
0
;
}
if
(
wt
[
n
-
1
] <=
W
) {
t
[
n
-
1
][
W
-
wt
[
n
-
1
]] =
knapsack
(
wt
,
value
,
W
-
wt
[
n
-
1
],
n
-
1
);
// Include item in the bag. In that case add the value of the item and call for the remaining items
int
tmp1
=
value
[
n
-
1
] +
t
[
n
-
1
][
W
-
wt
[
n
-
1
]];
// Don't include the nth item in the bag anl call for remaining item without reducing the weight
int
tmp2
=
knapsack
(
wt
,
value
,
W
,
n
-
1
);
t
[
n
-
1
][
W
] =
tmp2
;
// include the larger one
int
tmp
=
tmp1
>
tmp2
?
tmp1
:
tmp2
;
t
[
n
][
W
] =
tmp
;
return
tmp
;
// If Weight for the item is more than the desired weight then don't include it
// Call for rest of the n-1 items
}
else
if
(
wt
[
n
-
1
] >
W
) {
t
[
n
][
W
] =
knapsack
(
wt
,
value
,
W
,
n
-
1
);
return
t
[
n
][
W
];
}
return
-
1
;
}
// Driver code
public
static
void
main
(
String
args
[]) {
int
[]
wt
= {
1
,
3
,
4
,
5
};
int
[]
value
= {
1
,
4
,
5
,
7
};
int
W
=
10
;
t
=
new
int
[
wt
.
length
+
1
][
W
+
1
];
Arrays
.
stream
(
t
).
forEach
(
a
->
Arrays
.
fill
(
a
, -
1
));
int
res
=
knapsack
(
wt
,
value
,
W
,
wt
.
length
);
System
.
out
.
println
(
"Maximum knapsack value "
+
res
);
}
}
Back
|
FazBrowse Home
|
New Git URL