假设我有常量3、5、6、9、10。如何检测如何用最少的项数将$n$(输入)写成这些常量的和?
例子:
$n=10, S=10
$n=18, S=9+9
$n=24, S=9+9+6
$n=27, S=9+9+9
$n=28, S=10+9+9
谢谢
假设我有常量3、5、6、9、10。如何检测如何用最少的项数将$n$(输入)写成这些常量的和?
例子:
$n=10, S=10
$n=18, S=9+9
$n=24, S=9+9+6
$n=27, S=9+9+9
$n=28, S=10+9+9
谢谢
这是另一种Python解决方案,但希望您能轻松将其转换为PHP(我不是PHP专家,所以不会自己做 - 我相信您可以做得更好)。我尽量不使用任何高级Python函数,以便非Python读者更容易理解,但如果有些Python语法不清楚,请随时询问。
allowed = [3, 5, 6, 9, 10]
n = 28
solutions = [ None ] * (n + 1)
solutions[0] = []
for i in range(n + 1):
if solutions[i] is None: continue
for a in allowed:
if i + a > n: continue
if solutions[i + a] is None or len(solutions[i]) + 1 < len(solutions[i + a]):
solutions[i + a] = solutions[i] + [a]
print solutions[28]
它的工作原理是从0开始构建到所需数字,为每个可能的总数保留最短解决方案的缓存。它的运行时间为O(n * a),其中a是允许的不同值的数量。
顺便说一句,你对于n=28的答案是错误的。正确答案应该是[9, 9, 10]。
更新:这是我尝试使用PHP解决问题的代码:
<?php
$allowed = array(3, 5, 6, 9, 10);
$n = 28;
$solutions = array();
$solutions[0] = array();
foreach (range(0, $n) as $i) {
if (is_null($solutions[$i])) continue;
foreach ($allowed as $a) {
if ($i + $a > $n) continue;
if (is_null($solutions[$i + $a]) ||
sizeof($solutions[$i]) + 1 < sizeof($solutions[$i + $a])) {
$solutions[$i + $a] = array_merge($solutions[$i], array($a));
}
}
}
var_dump($solutions[$n]);
?>
它给出了正确的答案,但请注意我不是专业的PHP编码人员 - 我只是在PHP文档中查找了相应的函数。
$C
是您的整数集合,$S
是解决方案。$n = 28;
$C = array(3, 5, 6, 9, 10);
$S = array(array());
// if your set isn't sorted already, you have to call sort()
//sort($C);
for ($i = 0; $i <= $n; ++$i)
{
if (!isset($S[$i]))
{
continue;
}
foreach ($C as $v)
{
if ($i + $v > $n)
{
break;
}
if (!isset($S[$i + $v])
|| count($S[$i + $v]) > 1 + count($S[$i]))
{
$S[$i + $v] = $S[$i];
$S[$i + $v][] = $v;
}
}
}
print_r($S[$n]);
一个不可扩展但正确的解决方案草图(抱歉,目前只有Python..):
#!/usr/bin/env python
import itertools, sys
pool = [3, 5, 6, 9, 10]
repeat, found, solutions = 1, False, set()
try: x = int(sys.argv[1])
except: x = 42
while not found:
for n in itertools.product(pool, repeat=repeat):
s = sum(n)
if s == x:
solutions.add(n)
found = True
break
repeat = repeat + 1
print solutions
将产生:
$ python 1850629.py 11
set([(5, 6)])
$ python 1850629.py 19
set([(9, 10)])
$ python 1850629.py 21
set([(3, 9, 9)])
$ python 1850629.py 42
set([(3, 9, 10, 10, 10)])
PHP
,只是让你知道一下 :) - Doug Neiner有两种明显的方法:
找出所有可能的解决方案,使得“S=3A+5B+6C+9D+10E”,然后选择具有最多A、B、C、D、E值为0的解决方案。
A+B+C+D+E
。这不一定是具有最多零值的...是吗? - Stephen C除了已经提供的优秀通用答案外,还要记住,如果您的值集具有某些属性,则存在更优化的解决方案。
具体而言,如果您的解决方案是“最小的”-也就是说,任何值都存在一个最佳解决方案-那么您可以使用“贪心”算法找到最少数量的元素:只需添加最大值,直到余数小于它,然后重复使用下一个最大值,以此类推。
例如,许多国家用于货币的面额为0.01、0.02、0.05、0.10、0.20、0.50、1、2、5等。这个集合是最小的,因此您可以重复添加最大的有效面额。