The game can be played by two or more than two players. It consists of a chessboard(棋盘)and some chessmen(棋子), and all chessmen are marked by a positive integer or “start” or “end”. The player starts from start-point and must jumps into end-point finally. In the course of jumping, the player will visit the chessmen in the path, but everyone must jumps from one chessman to another absolutely bigger (you can assume start-point is a minimum and end-point is a maximum.). And all players cannot go backwards. One jumping can go from a chessman to next, also can go across many chessmen, and even you can straightly get to end-point from start-point. Of course you get zero point in this situation. A player is a winner if and only if he can get a bigger score according to his jumping solution. Note that your score comes from the sum of value on the chessmen in you jumping path.
Your task is to output the maximum value according to the given chessmen list.
问题重述:1. 只能向前跳;2. 下一个数必须大于前一个数;3. 找序列和的最大值。
解题思路:
举个例子:[5, 4, 6, 3, 17, 10, 11]
假设以序列中的第1个数:5,作为起始点,那么满足条件的有:
第3个数:6
第5个数:17
第6个数:10
第7个数:11
也就是所,以第一个数作为起点,下一个点就只能是上述的4个点中的任意一个。
现在就可以将原问题分接为以下问题:
从
[6, 3, 17, 10, 11] [17, 10, 11] [10, 11] [11]
这4个子序列中,找出以每个子序列的第1个数起点的最大子序列和。
到此,我们就已经将一个大问题分解成4个子问题。这样,反复迭代分解,就可以达到只有1个数的序列的情况,此时就可以停止分解,返回当前的这个数。
由于这个方法在执行过程中会进行大量的重复计算,所以为了避免重复计算,将中间的计算结果数据保存即可。
下面展示一些 内联代码片
。
goal_list = [5, 4, 6, 3, 17, 10, 11]
goal_dict = {} # 保存中间结果
def find_road(n):
global goal_list, goal_dict
if n == len(goal_list):
return n
max_num = 0
for x in range(n + 1, len(goal_list)):
if goal_list[x] > goal_list[n]:
if x not in goal_dict.keys():
goal_dict[x] = find_road(x)
max_num = max(goal_dict[x], max_num)
return goal_list[n] + max_num
print(find_road(0))
print(goal_dict)
输出结果:
32
{4: 17, 6: 11, 5: 21, 2: 27}
import random
goal_list = [random.randint(1, 50) for _ in range(20)]
goal_dict = {}
print(goal_list)
输出结果:
[13, 50, 31, 10, 8, 3, 43, 26, 13, 40, 22, 22, 29, 37, 42, 14, 35, 14, 45, 16]
# 重新执行函数:
print(find_road(0))
print(goal_dict)
输出结果:
192
{1: 50, 18: 45, 6: 88, 14: 87, 9: 127, 13: 124, 16: 80, 2: 158, 12: 153, 7: 179, 10: 175, 11: 175, 19: 16, 15: 94, 17: 59}