【问题标题】:Dynamic Programing to solve subset of given sum动态规划求解给定总和的子集
【发布时间】: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。现在我无法打印使之成为现实的玩家的索引。因此,如果有人可以帮助我打印一组得分等于总分的球员的指数,我将不胜感激。我不需要打印所有组合。

如果您不明白,也请提出任何问题,因为我不是以英语为母语的人。

【问题讨论】:

标签: java algorithm dynamic-programming


【解决方案1】:

好的,在您创建和更新布尔数组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);              
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-20
    • 2015-05-06
    • 1970-01-01
    • 2014-06-26
    • 1970-01-01
    • 1970-01-01
    • 2015-03-24
    • 2018-06-11
    相关资源
    最近更新 更多