Last active
March 23, 2019 13:33
-
-
Save wintercn/5596588 to your computer and use it in GitHub Desktop.
现在有1分、2分、5分的硬币各无限枚,要凑成1元有多少种凑法?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
动态规划(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];
}
我厂前端同学的解法(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 .. ]]]
就是动态规划吗?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
居然有这么奇葩的方法,看懂真累。。不过这代码风格很有槽点啊。。