这解决了 On-Topic 中的“特定编程问题”
我正在处理来自 Amazon Software Interview 的面试问题
问题是“给定一个整数三角形,在不跳过的情况下找到最大和的路径。”
我的问题是你如何表示整数三角形?
我在 Triangle of Integers 上查过这个并看到一个三角形的整数看起来像
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
表示这样的东西的最佳方式(数据结构)是什么?我的想法是像
int[] r1 = {1};
int[] r2 = {2, 3};
int[] r3 = {4, 5, 6};
int[] r4 = {7, 8, 9, 10};
int[] r5 = {11, 12, 13, 14, 15};
这是表示这个三角形整数结构的最佳方式吗?我考虑过使用二维矩阵结构,但它们必须具有相同大小的数组。
最佳答案
您应该将它们放在线性内存中并按以下方式访问它们:
int triangular(int row){
return row * (row + 1) / 2 + 1;
}
int[] r = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
for(int i=0; i<n_rows; i++){
for(int j=0; j<=i; j++){
System.out.print(r[triangular(i)+j]+" ");
}System.out.println("");
}
row, column
if row>column:
index=triangular(row)+column
因为它是一个可预测的结构,所以有一个表达式表示每行开头的偏移量。这将是最有效的方式。
关于java - 如何表示整数的三角形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28641948/