问题描述
(图3.1-1)示出了一个数字三角形。 请编一个程序计算从顶至底的某处的一条路
径,使该路径所经过的数字的总和最大。
●每一步可沿左斜线向下或右斜线向下走;
●1<三角形行数≤100;
●三角形中的数字为整数0,1,…99;
.
(图3.1-1)
径,使该路径所经过的数字的总和最大。
●每一步可沿左斜线向下或右斜线向下走;
●1<三角形行数≤100;
●三角形中的数字为整数0,1,…99;
.
(图3.1-1)
输入格式
文件中首先读到的是三角形的行数。
接下来描述整个三角形
接下来描述整个三角形
输出格式
最大总和(整数)
样例输入
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
样例输出
30
<span style="font-size:14px;">import java.util.Scanner;
public class Main{
public static int[][] m;
public static int n;
/*刚开始用递归写,超时了,后来改成循环,动态规划写通过了。
private static int solve(int x,int y){
if(x==n-1){
return m[x][y];
}else{
return m[x][y]+Math.max(solve(x+1,y), solve(x+1,y+1));
}
}
*/
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = new int[n][n];
for(int i=0;i<n;i++){
for(int j=0;j<=i;j++){
m[i][j]=sc.nextInt();
}
}
for(int i=n-1;i>=1;i--){
for(int j=0;j<i;j++){
m[i-1][j]+=Math.max(m[i][j], m[i][j+1]);
}
}
System.out.println(m[0][0]);
// System.out.println(solve(0,0));
}
}</span>