您的位置:首页 > 编程语言 > Java开发

Java进阶之欧拉工程 第十八篇【 找出从三角形顶端走到底端的最大和】

2014-08-18 20:19 381 查看
最大路径的寻找

题目如下:

从下面的三角形的顶端开始,向下面一行的相邻数字移动,从顶端到底端的最大总和为23.

3

7 4

2 4 6

8 5 9 3

也就是 3 + 7 + 4 + 9 = 23.

找出从以下三角形的顶端走到底端的最大总和:

75

95 64

17 47 82

18 35 87 10

20 04 82 47 65

19 01 23 75 03 34

88 02 77 73 07 63 67

99 65 04 28 06 16 70 92

41 41 26 56 83 40 80 70 33

41 48 72 33 47 32 37 16 94 29

53 71 44 65 25 43 91 52 97 51 14

70 11 33 28 77 73 17 78 39 68 17 57

91 71 52 38 17 14 91 43 58 50 27 29 48

63 66 04 68 89 53 67 30 73 16 69 87 40 31

04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
原题如下:

By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.
3

7 4

2 4 6

8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom of the triangle below:
75

95 64

17 47 82

18 35 87 10

20 04 82 47 65

19 01 23 75 03 34

88 02 77 73 07 63 67

99 65 04 28 06 16 70 92

41 41 26 56 83 40 80 70 33

41 48 72 33 47 32 37 16 94 29

53 71 44 65 25 43 91 52 97 51 14

70 11 33 28 77 73 17 78 39 68 17 57

91 71 52 38 17 14 91 43 58 50 27 29 48

63 66 04 68 89 53 67 30 73 16 69 87 40 31

04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem
67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o)
解题思路:看到这种求最大路径的问题,脑海里想到的第一个念头就是遍历,这里确实也可以这样做,不过请看原题的红字部分的提醒,这道题由于行数一共才15行,所以所有路径加起来只有16384条,但是67题与这道题类似,但是增加到了100行甚至可能更多,遍历这种最低效的办法就显然行不通了。所以必须想其他的算法,假设这里只有最后两行:
63 66 04 68 89 53 67 30 73 16 69 87 40 31

04 62 98 27 23 09 70 98 73 93 38 53 60 04 23

那么最优的算法显然是将第一行所有的数,分别加上这个数的相邻两个数中的大值,就能得到答案,推广到题目中的15行的话,也是使用这样的思想,从最低行开始,计算最末两行的最大路径,并且将结果依次替换倒数第二行的数字,此时得到的就是最后两行所有的最大路径,继续往上加一层,就能最末三行的所有最大路径,以此类推,当加到第一层的时候,由于第一层只有一个数字,剩下的唯一路径就是我们要求的最大路径了。java代码如下:

<div style="text-align: left;"><span style="font-family: 'courier new'; "> </span><pre name="code" class="java">public class Launcher {
public static void main(String[] args) throws FileNotFoundException {
int[][] array=new int[15][15];
int line=0;//标记第几行
BufferedReader readTxt=new BufferedReader(new FileReader(new File("X:/TriangleNum.txt")));//用来存放数字的txt文件

try {
String textLine="";
String  str="";
while((textLine = readTxt.readLine())!=null){//读取文件,循环条件为行不为空
textLine+=" ";
str=textLine;
String[] numList=str.split(" ");//一“”为分割每个数字,分别存入数组numList中

array[line]=new int[numList.length];

for(int i=1;i<numList.length;i++){
array[line][i-1]=(Integer.parseInt(numList[i]));
}
line++;
}
for(int i=13;i>=0;i--){
for(int j=0;j<=i+1;j++){
array[i][j]+=(array[i+1][j]>array[i+1][j+1])?array[i+1][j]:array[i+1][j+1];
}
}
System.out.println(array[0][0]);

readTxt.close();
} catch (IOException e){
// TODO Auto-generated catch block
e.printStackTrace();
}

}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: