给出以下输入
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.我不需要打印两种或所有组合。我只想打印任何一种有效的组合。
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];
}
此逻辑创建2d数组并进行穷举搜索以查看给定总数的组合是否可行,如果是,则返回true,否则返回false。现在我无法打印出真实的玩家的索引。如果有人可以帮我打印一组得分等于总数的球员的索引,那将非常感激。我不需要打印所有组合。
如果您不理解,我也不会问任何问题,因为我不是以英语为母语的人。
答案 0 :(得分:2)
好的,所以在你创建并更新了布尔数组myArray
之后。
我们将从最后一个玩家迭代到第一个玩家,检查我们是否可以在最终结果中使用当前玩家
int currentScore = total;//Maintain the current score.
for(int i = lastPlayer ; i >= 0; i--){
}
在for循环中,为了检查当前i
玩家是否属于我们的最终玩家,我们需要检查是否存在currentScore - score of i player
的解决方案
if (currentScore >= scores[i] && (i == 0 || myArray[i - 1][currentScore - scores[i]]) {
//Update current score
currentScore -= scores[i];
//Print name of the player.
System.out.println("Player " + i);
}