我以错误的方式解决了Project Euler#15。为什么这样做?

时间:2015-11-23 03:40:33

标签: ruby binomial-coefficients

# Starting in the top left corner of a 2×2 grid, 
# and only being able to move to the right and down, 
# there are exactly 6 routes to the bottom right corner.
# How many such routes are there through a 20×20 grid?


def lattice_paths
  a = (0..19).to_a
  puts a.repeated_combination(a.length).to_a.length * 2
end

lattice_paths

这解决了它,虽然我的电脑花了一个多小时。我手工做了3x3网格,以检查生产中的解决方案。

事后研究,我发现了这个二项式系数:

f(n)=(2n-1; n)

但即使经过一个小时的研究如何计算这些,我仍然不知道如何手工完成,更不用说通过Ruby了。

3 个答案:

答案 0 :(得分:2)

r事物的n长度的重复组合数等于(n + r - 1; r)。有关原因,请参阅this website(标题为“#34;重复组合"”部分)。

在您的代码中,rn相同,因此您可以将其写为(2n - 1; n),这是a.repeated_combination(a.length).to_a.length返回的内容。将此值乘以2会在此特定情况下得出(2n; n)(因为(2x - 1; x) * 2对于所有整数(2x; x)等于x,这是正确的答案。

答案 1 :(得分:2)

@Brad的权利(或几乎正确 - 不确定)。这就是原因。对于nxn网格(即n行和n列),从左上角到右下角的每条路径向下移动n-1n-1向右移动。此类路径的数量等于从n-1总移动中选择2*(n-1)右移(或向下移动)的方式的数量:

(total moves)!/(right moves)!*(total moves - right moves)!
  #=> (total moves)!/(right moves)!**2
  #=> (2*(n-1))!/(n-1)!**2

对于n=20,这是:

38!/19!**2

n=21

40!/20!**2

这是@Brad的回答。对于n=3,有:

4!/2!**2 #=> 6

路径。问题是“2x2”网格“有6条路径,因此我必须将其视为”3x3“网格。我希望这种解释上的差异也能解释为什么Brad的答案与我的n=21案例相对应。

答案 2 :(得分:1)

我刚才在Ruby中解决了这个问题。

我不知道它是如何工作的,但它给出了正确答案。

puts (1..40).inject(:*) / (1..20).inject(:*) ** 2