Skip to content

Instantly share code, notes, and snippets.

@wintercn
Last active March 23, 2019 13:33
Show Gist options
  • Save wintercn/5596588 to your computer and use it in GitHub Desktop.
Save wintercn/5596588 to your computer and use it in GitHub Desktop.
现在有1分、2分、5分的硬币各无限枚,要凑成1元有多少种凑法?
function getResult(n,coins) {
var a = new Array(n+1);
for(var i = 0; i <= n;i++)
a[i] = 0;
a[0] = 1;
for(var j = 0; j<coins.length; j++)
for(var i = 0; i <= n;i++)
a[i+coins[j]] += a[i];
return a[n];
}
getResult(100,[1,2,5]); // 541
@themez
Copy link

themez commented May 18, 2013

居然有这么奇葩的方法,看懂真累。。不过这代码风格很有槽点啊。。

@TerenceZ
Copy link

动态规划(Dynamic Programming),这个问题属于完全背包问题那一类,还有其他像整数拆分之类的和这个代码几乎一样,只是初始条件可能会有所不同。PS:确实代码风格有一处有槽点啊,a[101..105]全是NaN:)
也许改成下面这样会好理解点。

function getResult(coins, n) {
  var a = new Array(n+1);

  for (var i = 1; i <= n; ++i) a[i] = 0;

  a[0] = 1;

  for (var i = 0; i < coins.length; ++i)
    for (var j = coins[i]; j <= n; ++j) // Here
      a[j] += a[j-coins[i]]; //  and here!

  return a[n];
}

@hax
Copy link

hax commented May 20, 2013

我厂前端同学的解法(haskell):

module Main where
    coin :: Int -> Int
    coin 0 = 0
    coin n = sum $ map (\a -> (a `div` 2 + 1)) $ takeWhile (>=0) [a | a <- [n - (5 * b) | b <- [0 .. ]]]

详见http://zhanglin.pro/19

@yuanyuanlife
Copy link

就是动态规划吗?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment