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