【发布时间】:2016-04-26 15:56:26
【问题描述】:
一个数组作为用户的输入。该数组包含整数。添加一些、全部或仅添加一个就足够了,使总和尽可能接近 100。
- 数组可以包含 1-100 个整数
- 数组中的每个整数的值都在 1-100 之间,有些可能相同。数组中的随机顺序出现
- 没有限制应该添加多少才能尽可能接近 100
- 如果有几种组合是可能的或给出相同的答案同样接近 100,如 99 和 101,则应选择最高的。
我的问题是我真的不知道如何处理循环。我尝试过嵌套两个,但我发现不知道计算可能需要数组中有多少整数是很棘手的。
到目前为止,我的循环循环每个整数:
//looping over all integers in the array
for (int i = 0; i < myArray.length; i++) {
//check already here if it is close to 100?
//compare the integer above to the next
for (int j = i + 1; nextWeight < myArray.length; j++) {
//the results should be saved temporary to comparision to new sums
}
}
我知道这并不多,而且我知道它可能以某种方式涉及动态编程。
有人有什么想法可以帮助我吗?
【问题讨论】:
-
看看这个en.wikipedia.org/wiki/Knapsack_problem也许对你有帮助。
标签: java arrays loops compare target