Dynamic Programing approach for a subset sum

前端 未结 4 521
借酒劲吻你
借酒劲吻你 2021-01-15 09:20

Given the following Input

10 4 3 5 5 7

Where

10 = Total Score

4 = 4 players

3 = Score by player 1

5 = Score by player 2
         


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-15 09:58

    public List findSubsetWithSum(int[] score, int totalScore)
    {
        int players = score.length;
    
        int[] cameFrom = new int[totalScore+1];
        int[] pickedPlayer = new int[totalScore+1];
        for (int s = 0; s <= totalScore; s++)
        {
            cameFrom[s] = -1;
            pickedPlayer[s] = -1;
        }
        cameFrom[0] = 0;
        for (int p = 0; p < players; p++)
        {
            for (int s = score[p]; s <= totalScore; s++)
            {
                if (cameFrom[s - score[p]] >= 0)
                {
                    cameFrom[s] = s - score[p];
                    pickedPlayer[s] = p + 1;
                }
            }
        }
        List picked = new ArrayList();
        for (int s = totalScore; s > 0 && cameFrom[s] >= 0; s = cameFrom[s])
        {
            picked.add(pickedPlayer[s]);
        }
        return picked;
    }
    

提交回复
热议问题