Find all subsets that sum to a particular value and then pick the most valuable combination of those subsets

半世苍凉 提交于 2021-02-08 04:48:38

问题


Im trying to create a simple dice game. To calculate the score i have to find all subsets that sum to a particular value and then pick the most valuable combination. All numbers can only be picked once. Probably easiest to describe with an example:

Values =  {1, 1, 1, 2, 4, 4}

Target value = 5

Possible subsets = {1, 1, 1, 2} and {1, 4}

Now its possible to either choose:

{1, 1, 1, 2} (= worth 5)

or

{1, 4} {1, 4} (= worth 10)

So in this example I would like the algorithm to return 10 and not 5.

I have managed to solve the 'finding possible subsets' part but im struggling to find the most valuable combination of the found subsets. Can anyone help me? :(


回答1:


Since you have managed to find the combinations, I will just concentrate on grouping them. First of all, we need to make sure that we know whenever two groups are equal.

{1,4} is equal to {1,4}

{1,4} is equal to {4,1} ?

{1,4} is different from {1,1,1,2}

So, you will need to make sure your program can do a proper comparison. For this purpose, you will need to generate a "signature" of a combination, that's a value (for example a string) so whenever you are interested whether two groups are equal, you compare their signature. You will need to have a data structure (a Map) of singature and number, which would store all the occurred signatures and their occurrence number. Whenever you get a combination, you will need to find out whether the map contains the given signature. If so, increment the occurrence. If not, add the signature to the map with a value of 1. After you found all combinations, find the entry in the map with the largest value and that will be the solution.

Now, let's get back to the question of whether

{1,4} equals {4,1}?

If the two are equal, then you will need to sort the items of a combination before you generate its signature. If the two are not equal (that would mean that we are dealing with variations), then you do not need to sort the items, just generate the signature in their raw form.



来源:https://stackoverflow.com/questions/54615250/find-all-subsets-that-sum-to-a-particular-value-and-then-pick-the-most-valuable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!