码迷,mamicode.com
首页 > 其他好文 > 详细

Project Euler:Problem 15 Lattice paths

时间:2015-05-31 09:26:08      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:c++   project euler   

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][n]=res[m-1][n]+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;
}




Project Euler:Problem 15 Lattice paths

标签:c++   project euler   

原文地址:http://blog.csdn.net/youb11/article/details/46278621

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!