Project Euler | Problem 015

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?

网格路径

从一个 2 × 2网格的左上角出发,若只允许向右或向下移动,则恰好有 6条抵达右下角的路径。

对于 20 × 20网格,这样的路径有多少条?


显然这是一个组合问题:结果是C _{row + col}^{row}\textrm{}

/*
*	Program 1
* 思路:
*	1.组合问题,运用组合公式计算;
* 收获:
*	1.1.记录日志结合递归提高效率
* 评价:
*	优点:
*		1.空间换效率,减少栈溢出风险
*	缺点:
*		1.现有数据结构已经无法储存阶乘的结果,
*         直接使用阶乘公式将出现数据丢失
*		2.开辟堆空间对数据进行储存
*		3.将重点放在了优化计算组合数
*/

#define _CRT_SECURE_NO_WARNINGS
#define ROW 20
#define COL 20

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

//计算网格路径
static int LatticePaths(const int row, const int col)
{
	assert(row);
	assert(col);

	int factor1st = row + col;
	int factor2nd = row;

	int* arr = (int*)calloc(row + 1, sizeof(int)); //收获1.1
	if (arr == NULL)
	{
		perror("LatticePaths");
	}
	for (int i = 0; i < row + 1; i++)//生成每一个因数及其伴随着的标记
	{
		arr[i] = i;
	}

	int ret = 1;
	while (factor1st > row && factor2nd >= 0)
	{
		ret *= factor1st;
		for (int i = 1; i <= row; i++)
		{
			if (arr[i] && ret % arr[i] == 0)//标记每一个因数,使之只做一次除法
			{
				ret /= arr[i];
				arr[i] = 0;
				factor2nd--;
			}
		}
		factor1st--;
	}

	free(arr);
	arr = NULL;
	return ret;
}

int main()
{
	printf("%d\n", LatticePaths(ROW, COL));
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值