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?
第一版:最右下角的点,只有两条路径,所以到最右下角的点的路径数等于,那两条路径之和:array[n][n] = array[n-1][n] + array[n-1][n]
如此我们就可以递归求解。
def lattice(array,i,k):
if i > 0 and k >0:
array[i][k] =lattice(array,i-1,k) + lattice(array,i,k-1)
return array[i][k]
def run(n):
array = [ [ None for i in range(n+1) ] for j in range(n+1) ]
for i in range(n+1):
array[0][i] = 1
array[i][0] = 1
return lattice(array,n,n)
第二版:第一版中递归求解,从n --> 1 ,中间有大量的重复计算,非常耗时。从下图数据来看,如果我们从1--> n 来填充矩阵数据,我们就可以利用上之前计算结果。def lattice(n):
array = [ [ None for i in range(n+1) ] for j in range(n+1) ]
for i in range(n+1):
array[0][i] = 1
array[i][0] = 1
for i in range(1,n+1):
for j in range(i,n+1):
array[i][j] = array[i-1][j] + array[i][j-1]
array[j][i] = array[i][j]
return array[n][n]
第三版:从数学组合问题来看,在每一条路径中,都会有20次横向和20次纵向移动。如果将横向移动标记为1,纵向移动标记为0,那么问题就变成一个40位数字中有20个1和20个0的组合问题。所以答案就是C(20,40)。
def c(n,m):
r = 1
for i in range(n-m+1,n+1):
r *= i
for i in range(1,m+1):
r /= i
return r
参考:http://mathschallenge.net/full/random_routes