読者です 読者をやめる 読者になる 読者になる

mu chance or much chance ?

日々の戯れ言

Project Euler 31

Project Euler

Problem31を解きました.

  • Coin sums

In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation:

1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p).
It is possible to make £2 in the following way:

1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p
How many different ways can £2 be made using any number of coins?

https://projecteuler.net/problem=31

問題は「1p, 2p, 5p, 10p, 20p, 50p, £1, £2を使って£2を作る方法は何通りあるか求めよ」.

limit = 200
coin = [1, 2, 5, 10, 20, 50, 100, 200]
ans = Array.new(limit + 1, 0)
ans[0] = 1

for i in 0..coin.length - 1 do
  j = coin[i]
  while j <= limit
    ans[j] += ans[j - coin[i]]
    j += 1
    end
end

p ans

動的計画法を用いて求めています.