---
title: "问题18－求三角从顶到底的最大值"
author: "zhou_zhihao"
date: "2010-11-28T23:20:15Z"
tags: []
categories: ["编程语言"]
slug: "18"
draft: false
lastmod: "2010-11-30T21:40:57Z"
id: 827484
url: "https://clumsybird.iteye.com/blog/827484"
---

问题描述如下：

“如下的三角形，从顶部向下走时，只能走最临近的数，如下所示：

 **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

note：这里一共有16348条路从顶到底，如果每条路都走以下，可能会解决此问题。但是在问题67中，三角 形有100行，如果所有的路都去遍历，那么就不是很好了，可以想一些比较好的方法去解决此问题。”

 

代码实现如下：

problem18.txt

 

```
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
```

  java代码：

 

```
/**
	 * 初始化数组
	 */
	private static void init() {
		try {
			File f = new File("problem18.txt");
			FileReader fr = new FileReader(f);
			BufferedReader br = new BufferedReader(fr);
			String line = null;
			List<int[]> list = new ArrayList<int[]>();
			while ((line = br.readLine()) != null) {
				String[] s = line.split(" ");
				int[] temp = new int[s.length];
				for (int i = 0; i < s.length; i++) {
					temp[i] = Integer.parseInt(s[i]);
				}
				list.add(temp);
			}
			n = new int[list.size()][];
			list.toArray(n);
		} catch (Exception e) {
			// TODO: handle exception
		}
	} 
```

```
/**
	 * 从下往上看 
	 * 倒数第二行，在能选取倒数第一行的数中最大的求和
	 * 倒数第三行，在能选取倒数第二行与第二行之和的数最大的求和
	 * ...
	 * 
	 * @return
	 */
	private static int getMaxNumber() {
		int[] result;
		result = n[n.length - 1];
		for (int i = n.length - 2; i >= 0; i--) {
			int[] temp = n[i];
			for (int j = 0; j < temp.length; j++) {
				result[j] = temp[j] + Math.max(result[j], result[j + 1]);
			}
		}
		return result[0];
	}
```

   调用方法可以得到结果：1074

请不吝赐教。

@anthor ClumsyBirdZ