Project Euler:Problem 15 Lattice paths

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;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值