My problem is as follows-
I have some numbers with me, like below-
2
2
2
2
3
3
17
17
17
17
17
17
17
17
1开发者_Python百科7
34
34
34
34
34
68
68
68
136
So if I give the following number as input, the output should be as follows-
[output is the sum of given number, that just greater than the input]
Input Output
3 2,2
4 2,2
254 17,34,68,136
7 2,3,3 [or also with 2,2,2,2 but if return same sum,
then number count should min]
205 2,68,136
10 2,2,3,3
I don't just want to try each and every combination (i.e brute force) to get the result. So just want to ask is there any efficient algorithm possible for the above situation.
Thanks.
I found a possible starting point on Wikipedia:
A more general problem asks for a subset summing to a specified value (not necessarily 0). It can be solved by a simple modification of the algorithm above. For the case that each xi is positive and bounded by the same constant, Pisinger found a linear time algorithm.[3]
Your basic problem looks like an extended version of that. You need to find a subset of your set summing to input
- or failing that, summing to input+1
, or failing that, summing to input+2
, etc.
So just run Pisinger's algorithm repeatedly, with increasing target sums, until you get a result? (I haven't read the paper, so I don't know whether the tiebreaker condition of choosing the smallest subset is satisfied by Pisinger's algorithm.)
精彩评论