Skip to content
体验新版
项目
组织
正在加载...
登录
切换导航
打开侧边栏
Snowleopard_wu
Java
提交
e5a3e4b4
J
Java
项目概览
Snowleopard_wu
/
Java
与 Fork 源项目一致
从无法访问的项目Fork
通知
1
Star
0
Fork
0
代码
文件
提交
分支
Tags
贡献者
分支图
Diff
Issue
0
列表
看板
标记
里程碑
合并请求
0
Wiki
0
Wiki
分析
仓库
DevOps
项目成员
Pages
J
Java
项目概览
项目概览
详情
发布
仓库
仓库
文件
提交
分支
标签
贡献者
分支图
比较
Issue
0
Issue
0
列表
看板
标记
里程碑
合并请求
0
合并请求
0
Pages
分析
分析
仓库分析
DevOps
Wiki
0
Wiki
成员
成员
收起侧边栏
关闭侧边栏
动态
分支图
创建新Issue
提交
Issue看板
前往新版Gitcode,体验更适合开发者的 AI 搜索 >>
提交
e5a3e4b4
编写于
9月 22, 2020
作者:
ishellhub
浏览文件
操作
浏览文件
下载
电子邮件补丁
差异文件
reformat code
上级
c41d10ab
变更
1
隐藏空白更改
内联
并排
Showing
1 changed file
with
19 addition
and
30 deletion
+19
-30
DynamicProgramming/SubsetSum.java
DynamicProgramming/SubsetSum.java
+19
-30
未找到文件。
DynamicProgramming/SubsetSum.java
浏览文件 @
e5a3e4b4
...
...
@@ -2,15 +2,27 @@ package DynamicProgramming;
public
class
SubsetSum
{
/*
This algorithm will determine if a set of integers contains
a subset that sum to a given integer. The algorithm will
return true if such a subset exists and false otherwise.
This is a dynamic programming implementation.
/**
* 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
);
}
private
static
boolean
subsetSum
(
int
arr
[],
int
n
,
int
sum
){
boolean
isSum
[][]
=
new
boolean
[
n
+
2
][
sum
+
1
];
/**
* 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
++)
{
...
...
@@ -31,27 +43,4 @@ public class SubsetSum {
return
isSum
[
1
][
sum
];
}
/*
This is a driver method to run the algorithm with four
test values: the first two should evaluate true, and the
last two should evaluate false.
*/
public
static
void
main
(
String
args
[])
{
int
arr
[]
=
new
int
[]{
50
,
4
,
10
,
15
,
34
};
int
n
=
arr
.
length
;
// 4 + 10 + 15 + 34 = 64
int
sum1
=
64
;
// 50 + 15 + 34 = 99
int
sum2
=
99
;
// No subset of the given array will give a sum
// of 5 or 66
int
sum3
=
5
;
int
sum4
=
66
;
System
.
out
.
println
(
subsetSum
(
arr
,
n
,
sum1
));
System
.
out
.
println
(
subsetSum
(
arr
,
n
,
sum2
));
System
.
out
.
println
(
subsetSum
(
arr
,
n
,
sum3
));
System
.
out
.
println
(
subsetSum
(
arr
,
n
,
sum4
));
}
}
\ No newline at end of file
编辑
预览
Markdown
is supported
0%
请重试
或
添加新附件
.
添加附件
取消
You are about to add
0
people
to the discussion. Proceed with caution.
先完成此消息的编辑!
取消
想要评论请
注册
或
登录