注意:原始帖子中的问题陈述假设一个严格的直角三角形:
on each path the next number is located on the row below,
more precisely either directly below or below and one place to the right.
另请查看他们提供的示例以确认这一点。
回答:
1]使用二维数组来存储三角形
根据规则重新计算三角形
走三角形的最后一行——即底边——找到最大值。
代码:
import java.util.Arrays;
public class NumberTriangle {
//MAIN IS FOR TESTING ONLY
public static void main(String[] ars) {
int[][] input = { { 1 }, { 4, 8 }, { 9, 8, 7 }, { 1, 3, 6, 9 },
{ 7, 5, 2, 7, 3 } };
int max = compute(input);// answer: max length
// not necessary; but shows new triangle
for (int[] A : input)
System.out.println(Arrays.toString(A));
// print the answer
System.out.println("Largest number: " + max);
}
//THIS IS THE SOLUTION
public static int compute(int[][] input) {
//compute new triangle
for (int y = 1; y < input.length; y++)
for (int x = 0; x < input[y].length; x++) {
int first = x - 1 > 0 ? x - 1 : 0;
int last = x < input[y - 1].length ? x
: input[y - 1].length - 1;
int max = Math.max(input[y - 1][last], input[y - 1][first]);
input[y][x] += max;
}
//extract max value;
int max = -1;
int lastRow = input[input.length - 1].length;
for (int x = 0, y = input.length - 1; x < lastRow; x++)
if (max < input[y][x])
max = input[y][x];
return max;
}// compute
}
测试用例答案:
[1]
[5, 9]
[14, 17, 16]
[15, 20, 23, 25]
[22, 25, 25, 32, 28]
Largest number: 32