当下,坐公交或者地铁时大部分人都是刷卡的。不过,时至今日还在用现金支付的人仍是比想象的多。本题咱们以安置在公交上的零钱兑换机为背景。
这个机器能够用纸币兑换到 10 日元、50 日元、100 日元和 500 日元硬币的组合,且每种硬币的数量都足够多(由于公交接受的最小额度为 10 日元,因此不提供 1 日元和 5 日元的硬币)。
兑换时,容许机器兑换出本次支付时用不到的硬币。此外,由于在乘坐公交时,若是兑换出了大量的零钱会比较不便,因此只容许机器最多兑换出 15 枚硬币。譬如用 1000 日元纸币兑换时,就不能兑换出“100 枚 10 日元硬币”的组合( 图5 )。
问题
求兑换 1000 日元纸币时会出现多少种组合?注意,不计硬币兑出的前后顺序。c++
package main import "fmt" const ( coin10 = 10 coin50 = 50 coin100 = 100 coin500 = 500 ) func mostCount(money, coinDeno int)int{ mostC := money / coinDeno if mostC > 15{ return 15 }else{ return mostC } } func main(){ money := 1000 coin10MostCount := mostCount(money, coin10) coin50MostCount := mostCount(money, coin50) coin100MostCount := mostCount(money, coin100) coin500MostCount := mostCount(money, coin500) n := 0 for a:=0;a<=coin500MostCount;a++ { for b:=0;b<=coin100MostCount;b++{ for c:=0;c<=coin50MostCount;c++{ for d:=0;d<=coin10MostCount;d++{ if 500*a + 100*b + 50*c + 10*d == money && a + b + c + d <= 15{ fmt.Printf("%d = 500*%2d + 100*%2d + 50*%2d + 10*%2d\n", money, a, b, c, d) n++ } } } } } fmt.Println("共", n, "种组合") }
结果:ide
1000 = 500* 0 + 100* 5 + 50*10 + 10* 0 1000 = 500* 0 + 100* 6 + 50* 8 + 10* 0 1000 = 500* 0 + 100* 7 + 50* 6 + 10* 0 1000 = 500* 0 + 100* 8 + 50* 4 + 10* 0 1000 = 500* 0 + 100* 9 + 50* 1 + 10* 5 1000 = 500* 0 + 100* 9 + 50* 2 + 10* 0 1000 = 500* 0 + 100*10 + 50* 0 + 10* 0 1000 = 500* 1 + 100* 0 + 50* 9 + 10* 5 1000 = 500* 1 + 100* 0 + 50*10 + 10* 0 1000 = 500* 1 + 100* 1 + 50* 7 + 10* 5 1000 = 500* 1 + 100* 1 + 50* 8 + 10* 0 1000 = 500* 1 + 100* 2 + 50* 5 + 10* 5 1000 = 500* 1 + 100* 2 + 50* 6 + 10* 0 1000 = 500* 1 + 100* 3 + 50* 3 + 10* 5 1000 = 500* 1 + 100* 3 + 50* 4 + 10* 0 1000 = 500* 1 + 100* 4 + 50* 0 + 10*10 1000 = 500* 1 + 100* 4 + 50* 1 + 10* 5 1000 = 500* 1 + 100* 4 + 50* 2 + 10* 0 1000 = 500* 1 + 100* 5 + 50* 0 + 10* 0 1000 = 500* 2 + 100* 0 + 50* 0 + 10* 0 共 20 种组合
貌似复杂,作起来其实不难,把各类状况都让计算机试一遍就行了。code