eBash

It is not the mountain we conquer but ourselves

Project Euler Problem 18

| Comments

1 Problem

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)

2 Solution

2.1 Brute Force

直接的方法就是brute force,但对于大数据量时速度会很慢.
对于n层高,共有 \(\frac{(n+1)n}{2}\) 个数字,由归纳法易知需要穷尽 \(2^{n-1}\) 条路径,每条路径上有n个数字,需要 \(\Theta(2^{n-1}n)\) 的时间, 易知数字总数m = \(\frac{(n + 2)(n + 1)}{2}\) ,则 m = \(\frac{\sqrt{1+8m}-3}{2}\),代入其中即得关于输入个数m的时间复杂度.

2.2 递归

2.2.1 分析

\(p_{i}\) 为第i个数字到最末层相邻数字相加最大值, \(a_{i}\) 为第i个数字的值, \(i\in(0,\frac{(n + 1)(n + 2)}{2})\)
题目所求为 \(p_{0}\) 的值,易知 \(p_{0}\) = max(\(p_{1}\), \(p_{2}\)) + \(a_{0}\) , \(p_{1}\) = max(\(p_{3}\), \(p_{4}\)) + \(a_{1}\) ,…
设共有n层高(从0开始),则对于i层(第 \(\frac{(i + 1)i}{2}\) ~ \(\frac{(i + 1)i}{2} + i\) 个数),以下等式成立:
\(p_{j}\) = max(\(p_{j + i + 1}\), \(p_{j + i + 2}\)) + \(a_{j}\) j \(\in[\frac{(i + 1)i}{2}\) , \(\frac{(i + 1)i}{2} + i]\)
\(p_{j}\) = \(a_{j}\) j \(\in[\frac{(n + 1)n}{2}\) , \(\frac{(n + 1)n}{2} + n]\)
对于n层高,其时间复杂度为 \(\Theta(\frac{(n+1)n}{2})\),易知数字总数m = \(\frac{(n + 2)(n + 1)}{2}\) ,则转换知对于输入个数m,其时间复杂度为 \(\Theta(m)\)

2.2.2 例子

对于原题中的例子其递归调用过程如下:

\(p_0\) = max(\(p_1\), \(p_2\)) + 3
\(p_1\) = max(\(p_3\), \(p_4\)) + 7
\(p_3\) = max(\(p_6\), \(p_7\)) + 2
\(p_6\) = 8
\(p_7\) = 5
\(p_3\) = 8 + 2 = 10
\(p_4\) = max(\(p_7\), \(p_8\)) + 4
\(p_8\) = 9
\(p_4\) = 9 + 4 = 13
\(p_1\) = 9 + 4 + 7 = 20
\(p_2\) = max(\(p_4\), \(p_5\)) + 4
\(p_5\) = max(\(p_8\), \(p_9\)) + 6
\(p_9\) = 3
\(p_5\) = 9 + 6 = 15
\(p_2\) = 9 + 6 + 4 = 19
\(p_0\) = 9 + 4 + 7 + 3 = 23

可以近似把所有数字看作一棵树,则为前序遍历,后序计算

2.3 Bottom-Up

2.3.1 分析

我们将上述递归算法转换为迭代,过程如下:
第n层时, \(p_{j}\) = \(a_{j}\) j \(\in[\frac{(n + 1)n}{2}\) , \(\frac{(n + 1)n}{2} + n]\)
第i层, \(p_{j}\) = max(\(p_{j + i + 1}\), \(p_{j + i + 2}\)) + \(a_{j}\) j \(\in[\frac{(i + 1)i}{2}\) , \(\frac{(i + 1)i}{2} + i]\)
与递归大抵类似.

对于输入个数n,其时间复杂度与递归类似为 \(\Theta(n)\), 如果 \(p_i\) 与 \(a_i\) 使用同一数组,则其空间复杂度为 \(\Theta(1)\)

2.3.2 例子

其计算过程如下:

   3                3             3          23
  7 4             7  4         20   19  
 2 4 6    ->    10 13 15   ->           ->  
8 5 9 3       

3 Answer

1074

Source:C++迭代 C++递归

Comments