你的问题是硬币问题和背包问题的混合体
如果硬币只使用一次:
给定一组值 S,n = |S|,m:要近似的值
DEFINE BEST = { }
DEFINE SUM = 0
DEFINE K = 0
WHILE S IS NOT EMPTY DO
K = K + 1
FIND MIN { Si : |(SUM+Si) - m| is minimal }
ADD TUPLE < Si, |(SUM+Si) - m|, K > to BEST
SUM = SUM + Si
REMOVE Si from S
END-FOR
RETURN BEST
该算法运行时间:O(|S| 2 ) ~ O(n 2 )
Set BEST 将有 n 个解,对于每个 K:1..n
for K:你在那个阶段有最优选择
找到完整的解决方案:
GIVEN BEST = { < COIN:X, DISTANCE:Y, DEGREE:K > }
DEFINE SOLUTION = { }
Y" = MINIMUM Y IN BESTi.Y for i: 1..n
KEEP ADDING BESTj.X to SOLUTION UNTILL BESTj.Y = Y" FOR j: 1..n
如果硬币可以重复使用:
DEFINE SOLUTION = { }
DEFINE SUM = 0
LESS = { Si : Si < m }
SORT LESS IN DESCENDING ORDER
FOR Li in LESS DO
WHILE (SUM+Li) <= m DO
SUM = SUM + Li
ADD Li TO SOLUTION
END-WHILE
IF SUM = m THEN BREAK-FOR
END-FOR
RETURN SOLUTION
在 JavaScript 中:
function coinProblem (var coins, var value)
{
var solution = new Array();
var sum = 0;
var less = new Array();
for (var i in coins)
if (i <= value)
less.push(i);
// sort in descending order
less.sort();
less.reverse();
for (var i in less)
{
while ((sum+i) <= value)
{
solution.push(i);
sum = sum + i;
}
if (sum == value) break;
}
return solution;
}