欧拉项目第15题 Lattice paths
2016-03-15 14:25
253 查看
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?
从左上开始,只允许往右和往下走,20*20的格子到右下角有多少中走法。
思路如下,将格子看成二维数组,如2*2格子,x[3][3],从x[0][0] 走到x[3][3],每次x[i][j],i加1或者j加1。
容易得出x[0][j]、x[i][0] = 1, x[i][j] = x[i-1][j] + x[i][j-1], x[i][j] = x[j][i]。
public static void main(String... args) {
Long[][] xx = new Long[21][21];
for(int i=0;i<21;i++){
for(int j=i;j < 21;j++) {
if(i == 0 || j==0) {
xx[i][j] = 1l;
xx[j][i] = xx[i][j];
continue;
} else if(xx[j][i] != null) {
xx[i][j] = xx[j][i];
} else {
xx[i][j] = xx[i-1][j] + xx[i][j-1];
xx[j][i] = xx[i][j];
}
}
}
System.out.println(xx[20][20]);
}
用integer中间会出现溢出,运行错误好几次,差点怀疑自己的思路。。。
How many such routes are there through a 20×20 grid?
从左上开始,只允许往右和往下走,20*20的格子到右下角有多少中走法。
思路如下,将格子看成二维数组,如2*2格子,x[3][3],从x[0][0] 走到x[3][3],每次x[i][j],i加1或者j加1。
容易得出x[0][j]、x[i][0] = 1, x[i][j] = x[i-1][j] + x[i][j-1], x[i][j] = x[j][i]。
public static void main(String... args) {
Long[][] xx = new Long[21][21];
for(int i=0;i<21;i++){
for(int j=i;j < 21;j++) {
if(i == 0 || j==0) {
xx[i][j] = 1l;
xx[j][i] = xx[i][j];
continue;
} else if(xx[j][i] != null) {
xx[i][j] = xx[j][i];
} else {
xx[i][j] = xx[i-1][j] + xx[i][j-1];
xx[j][i] = xx[i][j];
}
}
}
System.out.println(xx[20][20]);
}
用integer中间会出现溢出,运行错误好几次,差点怀疑自己的思路。。。
相关文章推荐
- PL/SQL使用
- nodejs4.4.0安装Linux
- android 多线程数据库读写分析与优化
- js 中使用基础地址
- jQuery插件(cookie存值)
- 算法训练 最大的算式 【dfs】
- iOS根据2个经纬度计算距离
- 175 - Combine Two Tables
- Docker自定义安装
- mysql 的行转列
- (4.5.1.4)Import Project(Eclipse ADT, Gradle,etc)(包括导入第三方Project项目(不是jar包形式))
- mysql dump备份方式 mysql还原操作练习
- springmvc使用json自动转换
- 修复.MYI'; try to repair it
- 安卓视频播放器 一行代码快速实现视频播放,Android视频播放,AndroidMP3播放,安卓视频播放一行代码搞定,仿今日头条 Android视频播放器
- jQuery-serialize()输出序列化form表单值的方法
- 为何总是在无聊的事中浪费生命
- iOS Core Graphics 和 Core Animation
- c语言:利用指针变量,用函数实现将3个整数按从大到小的顺序输出
- UIPasteboard 粘贴板