【发布时间】:2015-05-06 05:09:14
【问题描述】:
给定以下输入
10 4 3 5 5 7
在哪里
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
我要打印综合得分加到总分中的球员,这样输出就可以
1 4 因为玩家 1 + 玩家 4 得分 = 3 + 7 -> 10 或者输出可以是 2 3 因为玩家 2 + 玩家 3 得分 = 5 + 5 -> 10
所以它与子集和问题非常相似。我对动态编程比较陌生,但是在获得有关 stackoverflow 的帮助并在线阅读动态编程教程并在线观看了过去 3 天的一些视频之后。到目前为止,我提供了以下代码。
class Test
{
public static void main (String[] args) throws java.lang.Exception
{
int[] test = {3,5,5,7};
getSolution(test,4,10);
}
//pass total score, #of players (size) and the actual scores by each player(arr)
public static int getSolution(int[] arr,int size, int total){
int W = total;
int n = size;
int[][] myArray = new int[W+1][size+1];
for(int i = 0; i<size+1; i++)
{
myArray[i][0] = 1;
}
for(int j =1; j<W+1; j++)
{
myArray[0][j] = 0;
}
for(int i =1; i<size+1; i++)
{
for(int x=1; x<W+1; x++)
{
if(arr[i] < x)
{
myArray[i][x] = myArray[i-1][x];
}
else
{
myArray[i][x] = myArray[i-1][x-arr[i]];
}
}
}
return myArray[n][W];
}
}
由于某种原因,我没有得到预期的结果。在过去的 7 个多小时里,我一直试图在这个问题中找到错误,但没有成功。如果有人可以帮助解决问题以获得所需的结果,我将不胜感激。
另外请原谅我的英语不是我的母语。
更新 我也不需要打印所有可能的等于分数的组合。我可以打印任何等于分数的组合,就可以了。
【问题讨论】:
-
main调用的大小为 3,而不是 4。这是有意的吗? -
第一:你的英语很棒!其次,我们是否受限于只考虑成对的学生分数? IE。如果输入是
10 2 3 4 1 4,我们可以结合2 3 4 1得到10吗? (4 名学生) -
错误@NathanTuggy 哎呀刚刚意识到......我会马上修复。
-
@AndyG 谢谢!是的,您可以根据需要组合任意数量的玩家的分数,只要他们加起来就是总分
-
@user2733436:恐怕你的问题是子集总和。最坏情况精确算法仍然具有指数时间复杂度。 IE。作为初学者,您最好尝试生成每个可能的学生子集,然后评估该子集的总和。
标签: java algorithm recursion dynamic-programming subset