Hello everyone, I am Xiaolan who loves to share, welcome to exchange and correct~
1 Zhenti
enter
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
output
27
2 Analysis
Difficulty factor : ⭐⭐
Exam Question Type: Dynamic Programming
Knowledge points involved: modules
Thought analysis:
1. Loop through
When encountering pyramid-shaped data, first build a double for loop, traverse each number, and perform a sum calculation O(∩_∩)O
2. Recursion formula
There are three cases for summation: the element is at the leftmost or the middle or the rightmost
3. Print the answer
The final print needs to be classified discussion, odd and even.
Because the title requires: "The difference between the number of times of going down to the left and the number of times of going down to the right cannot exceed 1"
Follow this rule for a while, and you will find that the answer must fall in the middle.
If n is an odd number, it will inevitably go to the middle number a[-1][n//2] in the first last row
and if n is an even number, take the maximum value of the middle two numbers max(a[-1 ][n//2-1],a[-1][n//2])
3 code
#DP-数字三角形
n=int(input())#5
dp=[list(map(int,input().split())) for i in range(n)]
for i in range(1,n): #1~n-1
for j in range(i+1): #0~i
if j==0: #最左边元素只能由右上方得到
dp[i][j]+=dp[i-1][j]
elif j==i: #最右边元素只能由左上方得到
dp[i][j]+=dp[i-1][j-1]
else: #中间元素取上方相邻两个最大值
dp[i][j]+=max(dp[i-1][j-1],dp[i-1][j])
if n%2==1: #奇数行,返回中间值
print(dp[-1][n//2])
else: #偶数行,返回中间两个的最大值
print(max(dp[-1][n//2-1],dp[-1][n//2])) #27
'''样例输入 样例输出 样例输入 样例输出
i\j 0 1 2 3 4 0 1 2 3 4 0 1 2 3 0 1 2 3
0 7 7 7 7
1 3 8 10 15 3 8 10 15
2 8 1 0 18 16 15 8 1 0 18 16 15
3 2 7 4 4 20 25 20 19 2 7 4 4 20 25 20 19
4 4 5 2 6 5 24 30 27 26 24
'''
Read tens of thousands of lines of code, press the button like a god, roll up your sleeves and work hard!