Euler project #18 approach

后端 未结 9 875
鱼传尺愫
鱼传尺愫 2020-11-30 22:23

I am looking into an Euler project. Specifically #18.
To sum up, the idea is to find the max path from a triangle:

   3
  7 4
 2 4 6  
8 5 9 3
<         


        
9条回答
  •  旧巷少年郎
    2020-11-30 23:09

    Since the rows are small in number you can use also recursion to compute the greatest sum :

    import sys
    def max_sum(i,j):
        if i==14:
            return a[i][j]
        return a[i][j]+max(max_sum(i+1,j),max_sum(i+1,j+1))
    a=[]
    for i in range(15):
        b=list(map(int,sys.stdin.readline().split()))
        a.append(b)
    print(max_sum(0,0))
    

    for question 67 -(Maximum path sum II) you can use memoisation:

    import sys
    d={}
    def max_sum(i,j):
        if (i,j) in d:
            return d[(i,j)]
        if i==99:
            return a[i][j]
        d[(i,j)]=a[i][j]+max(max_sum(i+1,j),max_sum(i+1,j+1))
        return d[(i,j)]
    a=[]
    for i in range(100):
        b=list(map(int,sys.stdin.readline().split()))
        a.append(b)
    print(max_sum(0,0))
    

提交回复
热议问题