FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
Java/DynamicProgramming/SubsetSum.java at master · happyyb/Java · GitHub
happyyb
/
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
/
SubsetSum.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
44 lines (38 loc) · 1.17 KB
Breadcrumbs
Java
/
DynamicProgramming
/
SubsetSum.java
Copy path
File metadata and controls
44 lines (38 loc) · 1.17 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
package
DynamicProgramming
;
public
class
SubsetSum
{
/** Driver Code */
public
static
void
main
(
String
[]
args
) {
int
[]
arr
=
new
int
[] {
50
,
4
,
10
,
15
,
34
};
assert
subsetSum
(
arr
,
64
);
/* 4 + 10 + 15 + 34 = 64 */
assert
subsetSum
(
arr
,
99
);
/* 50 + 15 + 34 = 99 */
assert
!
subsetSum
(
arr
,
5
);
assert
!
subsetSum
(
arr
,
66
);
}
/**
* Test if a set of integers contains a subset that sum to a given integer.
*
* @param arr the array contains integers.
* @param sum target sum of subset.
* @return {@code true} if subset exists, otherwise {@code false}.
*/
private
static
boolean
subsetSum
(
int
[]
arr
,
int
sum
) {
int
n
=
arr
.
length
;
boolean
[][]
isSum
=
new
boolean
[
n
+
2
][
sum
+
1
];
isSum
[
n
+
1
][
0
] =
true
;
for
(
int
i
=
1
;
i
<=
sum
;
i
++) {
isSum
[
n
+
1
][
i
] =
false
;
}
for
(
int
i
=
n
;
i
>
0
;
i
--) {
isSum
[
i
][
0
] =
true
;
for
(
int
j
=
1
;
j
<=
arr
[
i
-
1
] -
1
;
j
++) {
if
(
j
<=
sum
) {
isSum
[
i
][
j
] =
isSum
[
i
+
1
][
j
];
}
}
for
(
int
j
=
arr
[
i
-
1
];
j
<=
sum
;
j
++) {
isSum
[
i
][
j
] = (
isSum
[
i
+
1
][
j
] ||
isSum
[
i
+
1
][
j
-
arr
[
i
-
1
]]);
}
}
return
isSum
[
1
][
sum
];
}
}
Back
|
FazBrowse Home
|
New Git URL