【发布时间】:2015-03-05 21:21:45
【问题描述】:
给定以下输入
10 4 3 5 5 7
Where
10 = Total Score
4 = 4 players
3 = Score by player 1
5 = Score by player 2
5 = Score by player 3
7 = Score by player 4
输出应该打印得分等于 10 的玩家的索引。因此对于上面给出的输出,它应该打印 1 4 或 2 3 因为玩家 1 + 玩家 4 的分数加起来为 10,玩家 2 和玩家的分数也是如此3. 我不需要打印 BOTH 或 ALL 组合。我只想打印任何一种有效的组合。
For INPUT : 8 3 2 2 4 OUPUT : 1 2 3 since scores of player 1 player 2 and player 3 equal the total score of 8
所以我过去一周一直在阅读动态编程教程和视频,并且还获得了有关堆栈溢出的帮助以修复我的初始代码。
以下是我目前所拥有的
public boolean findSolution(int[] scores, int total) {
int W = total;
int players = scores.length;
boolean[][] myArray = new boolean[players + 1][total + 1];
for (int player = 0; player <= players; player++) {
myArray[player][0] = true;
}
for (int score = 1; score < total; score++) {
myArray[0][score] = false;
}
for (int player = 1; player <= players; player++) {
for (int score = 1; score <= total; score++) {
myArray[player][score] = myArray[player - 1][score];
if (score >= scores[player - 1]) {
myArray[player][score] = myArray[player - 1][score
- scores[player - 1]]
|| myArray[player][score];
}
}
}
return myArray[players][W];
}
此逻辑创建二维数组并进行详尽搜索以查看给定总数的组合是否可能,如果是则返回 true,否则返回 false。现在我无法打印使之成为现实的玩家的索引。因此,如果有人可以帮助我打印一组得分等于总分的球员的指数,我将不胜感激。我不需要打印所有组合。
如果您不明白,也请提出任何问题,因为我不是以英语为母语的人。
【问题讨论】:
-
@erip 是重复的,但问题略有不同,如果有意义的话,我现在被困在不同的部分。否则对不起
标签: java algorithm dynamic-programming