开发者

Project Euler problem 67 not quite correct

I have the following Python code, which I wrote for the sister problem 18.

It works perfectly for problem 18, but is slightly out for problem 67. I can't for the life of me figure out why.

triangle = [
[59],
[73, 41],
[52, 40,开发者_如何学JAVA 9],
[26, 53, 6, 34],
[10, 51, 87, 86, 81],
[61, 95, 66, 57, 25, 68],
...
]

def max_adjacent(row,col):
    return max(triangle[row][col]+triangle[(row+1)][col], triangle[row][col]+triangle[(row+1)][(col+1)])

if __name__ == '__main__':
    row = len(triangle)-2
    while row >= 0:
        triangle[row] = [max_adjacent(row,triangle[row].index(i)) for i in triangle[row]]
        row -= 1
    print(triangle[0][0])

The algorithm is to start on the last-but-one row, and replace each number in this row with itself plus the largest adjacent number on the row below. (e.g., in the triangle partly defined above, 10 in the last but one row would be replaced with 105.) It simply loops this until it's at row 0 at the top of the triangle, and prints out the first element of this row, which is now the maximum sum.

This gives the answer of 7220, which I know to be close but wrong. I wonder why it works for problem 18 though?

Can anyone see what I'm assuming or doing wrong?


The problem might be that you're using the index function. If you have a number twice in a row, index will always give you the index of the number's first occurrence.

I guess Problem 18 has no duplicates within one row, the current problem has.


This code might help. Done in java using concepts of DP

 public static int max(int a,int b)
{
    return a>=b?a:b;
}
public static int maxSumPath(int a[][],int cacher[][],int r,int k) 
{
    if(r==100)
        return 0;
    else if(cacher[r][k]!=0)
    {
        return cacher[r][k];
    }
    else
    {
        cacher[r][k] = cacher[r][k] + max(maxSumPath(a,cacher,r+1,k),maxSumPath(a,cacher,r+1,k+1)) + a[r][k];
        return cacher[r][k];
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜