您的位置:首页 > 其它

Project Euler:Problem 15 Lattice paths

2015-05-30 21:48 274 查看
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?

很简单嘛~C(20,40)
但是在计算的时候遇到了麻烦,这个结果是有多大啊(╯‵□′)╯︵┻━┻
看来需要一边乘的同时一边除,同时还有注意精度问题



发现11~20间的数都能在上面找到对应的两倍数,化简一下:



#include <iostream>
using namespace std;

unsigned long long p(int a)
{
	unsigned long long res = 1;
	for (int i = 1; i <= a; i++)
	{
		res *= i;
	}
	return res;
}

int main()
{
	unsigned long long res = 1;
	for (int i = 39; i >= 21; i--)
	{
		res = res*i;
		i--;
	}
	res = res * 1024;
	res = res / p(10);
	cout << res << endl;
	system("pause");
	return 0;
}


上面是比较呆滞的解法,下面用递归来解决:
从点(1,1)到点(m,n)的路径数为:res[m]
=res[m-1]
+res[m][n-1] res[1][1]=1 res[1][0]=0 res[0][1]=0

因为到达点(m,n),可以是从点(m-1,n)来的,也可以是从(m,n-1)来的

初始点的坐标为(1,1),终点的坐标点应该为(m+1,n+1)
所以初始的res应该为22*22的二维数组。
#include <iostream>
using namespace std;

int main()
{
	unsigned long long res[22][22];
	memset(res, 0, sizeof(res));
	for (int i = 1; i <= 21; i++)
	{
		for (int j = 1; j <= 21; j++)
		{
			if (i == 1 && j == 1)
				res[i][j] = 1;
			else
				res[i][j] = res[i - 1][j] + res[i][j - 1];
		}
	}
	cout << res[21][21] << endl;
	system("pause");
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: