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间的数都能在上面找到对应的两倍数,化简一下:
上面是比较呆滞的解法,下面用递归来解决:
从点(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的二维数组。
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; }
相关文章推荐
- swf文件分析 转
- 软考之路--算法
- swf文件格式解析入门(tag解析)
- 【算法】一致性哈希算法详解
- swf文件格式解析入门(文件头解析)
- 编程之美第三题 序列变换tiyi
- Java代码 实现直接选择排序
- Xcode開發環境用什麼字體好?
- HDU 2000 ASCII码排序
- 【十二】队列及其顺序存储结构
- DFS&Iteration Binary Tree Postorder Traversal
- HDU--3333(树状数组+离线处理)
- [Swust OJ 1139]--Coin-row problem
- Joel 技术分享心得
- 【PS后期】一个蛋糕的故事
- Android 中双击退出
- Android 记录2 对于Android事件分发的理解
- JavaScript 开发的45个经典技巧
- 【末世旅行之C++】C++中的虚函数和纯虚函数的理解
- iOS layoutSubviews视图重绘总结