问题
I'm currently creating a program in C# that would look for the lowest possible equal sum of two sets of numbers, in which you may repeat the numbers as many times as you want.
For example, I have these two sets { 10, 13, 18 }
and { 12, 16, 22 }
. The lowest possible sum that I can get is 28: (10 + 18)
and (12 + 16)
.
Another example is {5, 7, 9}
and {1, 2, 3}
. Lowest possible sum is 5: (5)
and (1+1+1+1+1)
or (1+2+2)
or (2+3)
and so on.
Any suggestions on where I can start? I'll actually be using 6 numbers per set and the numbers are in the hundreds / thousands mark.
回答1:
Maintain two sets, initialized from your input sets, and ordered by increasing numbers (e.g. using a tree-based set structure). Now compare the first (i.e. minimal) elements from the two sets. The smaller one you remove from its set, add all elements from the corresponding input set to that value, and insert the results. When both sets have the same minimal element, then you are done and that element is your least common equal sum.
来源:https://stackoverflow.com/questions/12959936/getting-least-common-equal-sum-and-combination-of-two-sets-of-numbers