package com.kingdz.algorithm.time201706;
import java.util.ArrayList;
import java.util.List;
/**
* <pre>
* 数字金字塔
* 6
* 7 3
* 2 9 4
* 3 5 1 8
* 6 2 7 7 4
* 如上的金字塔形状,从最上面的数字向下走,只能选相邻近的数字,不能跨行或跨列,保证到达最下面时经过的数字和最大
* </pre>
*
* @author kingdz
*
*/
public class Algo02 {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("6");
list.add("7 3");
list.add("2 9 4");
list.add("3 5 1 8");
list.add("6 2 7 7 4");
int[][] tower = new int[list.get(list.size() - 1).split(" ").length][list.size()];
// 根据输入构建二维数组
int i = 0;
for (String str : list) {
String[] array = str.split(" ");
int j = 0;
for (String tmp : array) {
tower[i][j] = Integer.parseInt(tmp);
j++;
}
i++;
}
// 进行计算求出最大值
int y = 0;
int sum = tower[0][y];
for (int x = 1; x < tower.length; x++) {
if (tower[x][y] > tower[x][y + 1]) {
sum = sum + tower[x][y];
} else {
sum = sum + tower[x][y + 1];
y = y + 1;
}
}
System.out.println(sum);
}
}
【算法】程序猿不写代码是不对的65
最新推荐文章于 2023-12-24 16:00:47 发布