问题是这样的:
A robot is located at the top-left corner of a 66 x 49 grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
Note: The grid below is 7x3, and is used to illustrate the problem. It is not drawn to scale.
How many possible unique paths are there?
这个问题可以很简单的用递归来描述:
初始状态为walk(1,1,&path)。
对于3*7的情况它工作的很好。但是对于66*49它要花很长的时间。所以必须想其它的方法解决它。下图是机器人走的路径中的两条。
机器人往右走一格用一个R来表示,往下走一格用一个D来表示。所以图中上面一条路径可以这样表示RRRRDRRD。然后交换一下它们的位置变成DRDRRRRR就是图中下面一条路径了。我们可以再随便交换下位置RDRDRRRR又是另外条路径了。所以这个问题就可以转化为求它们的全排列个数。这是个纯粹的数学问题。可以用到这样一个公式:
在n个物品中,n1是第一个物品出现的次数,n2是第二个物品出现的次数,······,nr是第r个物品出现的次数,其中n1+n2+······+nr=n,则对于给定的这n个物品的全排列数是n!/(n1!n2!···nr!)。
所以对于66*49这个问题的答案是(65+48)!/(65!48!)。结果一定是个很大的数,python又该登场了。
结果是:217920480449507966548600162883595
0.000117053983118 seconds