# 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了。
答案 0 :(得分:2)
r
事物的n
长度的重复组合数等于(n + r - 1; r)
。有关原因,请参阅this website(标题为“#34;重复组合"”部分)。
在您的代码中,r
与n
相同,因此您可以将其写为(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-1
并n-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