Golden Pyramid
Our Robo-Trio need to train for future journeys and treasure hunts. Stephan has built a special flat model of a pyramid. Now the robots can train for speed gold running. They start at the top of the pyramid and must collect gold in each room, choose to take the left or right path and continue down to the next level. To optimise their gold runs, Stephan need to know the maximum amount of gold that can be collected in one run.
Consider a tuple of tuples in which the first tuple has one integer and each consecutive tuple has one more integer then the last. Such a tuple of tuples would look like a triangle. You should write a program that will help Stephan find the highest possible sum on the most profitable route down the pyramid. All routes down the pyramid involve stepping down and to the left or down and to the right.
Tips: Think of each step down to the left as moving to the same index location or to the right as one index location higher. Be very careful if you plan to use recursion here.
Input: A pyramid as a tuple of tuples. Each tuple contains integers.
Output: The maximum possible sum as an integer.
题目大义: 数字金字塔, 找出从顶部到底部, 路径的最大和(即这条路径上的数字相加的和为最大)
经典的DP问题D[i][j] = max(D[i - 1][j], D[i - 1][j - 1]) + Pyramid[i][j]
1 def count_gold(pyramid): 2 """ 3 Return max possible sum in a path from top to bottom 4 """ 5 6 step = len(pyramid) 7 8 sub_sum = [[0 for row in range(0, step)] for col in range(0, step)] 9 10 sub_sum[0][0] = pyramid[0][0] 11 12 for i in range(0, step): 13 for j in range(0, i + 1): 14 if i >= 1: 15 if j >= 1 and sub_sum[i - 1][j - 1] + pyramid[i][j] > sub_sum[i][j]: 16 sub_sum[i][j] = sub_sum[i - 1][j - 1] + pyramid[i][j] 17 18 if sub_sum[i - 1][j] + pyramid[i][j] > sub_sum[i][j]: 19 sub_sum[i][j] = sub_sum[i - 1][j] + pyramid[i][j] 20 21 max_sum = 0 22 for each in sub_sum[step - 1][:step]: 23 if each > max_sum: 24 max_sum = each 25 26 #replace this for solution 27 return max_sum
其实这份代码类似C语言的实现
观摩zero_loss的python实现
1 def count_gold(pyramid): 2 py = [list(i) for i in pyramid] 3 for i in reversed(range(len(py)-1)): 4 for j in range(i+1): 5 py[i][j] +=(max(py[i+1][j], py[i+1][j+1])) 6 7 return py[0][0]
这个实现是从下往上走, 非常简洁;
Golden Pyramid