Skip to content
切换导航条
切换导航条
当前项目
正在载入...
登录
孙克
/
smf-core
转到一个项目
切换导航栏
切换导航栏固定状态
项目
群组
代码片段
帮助
项目
活动
版本库
流水线
图表
问题
0
合并请求
0
维基
网络
创建新的问题
作业
提交
问题看板
文件
提交
网络
比较
分支
标签
Commit c6f8f79c
由
孙克
编写于
2024-08-29 16:06:27 +0800
浏览文件
选项
浏览文件
标签
下载
电子邮件补丁
差异文件
找到和为某个数的组合
1 个父辈
adddb51c
隐藏空白字符变更
内嵌
并排
正在显示
1 个修改的文件
包含
40 行增加
和
4 行删除
src/main/java/com/neotel/smfcore/custom/luxsan/factory_c/wipstor/util/ManualWorkUtil.java
src/main/java/com/neotel/smfcore/custom/luxsan/factory_c/wipstor/util/ManualWorkUtil.java
查看文件 @
c6f8f79
package
com
.
neotel
.
smfcore
.
custom
.
luxsan
.
factory_c
.
wipstor
.
util
;
import
cn.hutool.core.util.RandomUtil
;
import
com.google.common.collect.Lists
;
import
com.neotel.smfcore.core.device.util.DataCache
;
import
com.neotel.smfcore.custom.luxsan.factory_c.common.util.CacheNameUtil
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.stereotype.Component
;
import
java.util.ArrayList
;
import
java.util.HashMap
;
import
java.util.List
;
import
java.util.Map
;
import
java.util.*
;
@Component
public
class
ManualWorkUtil
{
...
...
@@ -38,4 +37,41 @@ public class ManualWorkUtil {
return
cacheMap
.
containsKey
(
boxStr
);
}
public
static
void
findCombinations
(
List
<
Integer
>
numbers
,
int
target
)
{
// 使用HashMap来存储和值及其对应的组合次数
Map
<
Integer
,
List
<
Integer
>>
sumCounts
=
new
HashMap
<>();
sumCounts
.
put
(
0
,
new
ArrayList
<>());
// 初始化,和为0的组合有1种(即不选任何数)
for
(
int
num
:
numbers
)
{
Map
<
Integer
,
List
<
Integer
>>
temp
=
new
HashMap
<>(
sumCounts
);
// 复制当前的和值映射,避免在迭代过程中修改
for
(
Map
.
Entry
<
Integer
,
List
<
Integer
>>
entry
:
temp
.
entrySet
())
{
int
sum
=
entry
.
getKey
();
Integer
newSum
=
sum
+
num
;
if
(
newSum
<=
target
)
{
// 只考虑不超过target的和
List
<
Integer
>
oldValue
=
new
ArrayList
<>(
entry
.
getValue
());
if
(!
sumCounts
.
containsKey
(
newSum
)){
oldValue
.
add
(
num
);
sumCounts
.
put
(
newSum
,
oldValue
);
if
(
newSum
==
target
){
System
.
out
.
println
(
"找到和为 "
+
target
+
" 的组合为 "
+
oldValue
+
" 共:"
+
oldValue
.
size
());
return
;
}
}
}
}
}
System
.
out
.
println
(
sumCounts
.
size
());
}
public
static
void
main
(
String
[]
args
)
{
List
<
Integer
>
numbers
=
new
ArrayList
<>();
for
(
int
i
=
0
;
i
<
100
;
i
++)
{
numbers
.
add
(
1
);
}
int
target
=
101
;
findCombinations
(
numbers
,
target
);
}
}
编写
预览
支持
Markdown
格式
附加文件
你添加了
0
人
到此讨论。请谨慎行事。
Finish editing this message first!
Cancel
请
注册
或
登录
后发表评论