当前位置:首页 » Project Euler » 详细页

Maximum path sum II 题号:67 难度: 5 中英对照

By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.

3
7 4
2 4 6
8 5 9 3

That is, 3 + 7 + 4 + 9 = 23.

Find the maximum total from top to bottom in triangle.txt (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one-hundred rows.

NOTE: This is a much more difficult version of Problem 18. It is not possible to try every route to solve this problem, as there are 299 altogether! If you could check one trillion (1012) routes every second it would take over twenty billion years to check them all. There is an efficient algorithm to solve it. ;o)

Solution

使用动态规划,从倒数第二行开始计算。假设原三角为: ``` 3 7 4 2 4 6 8 5 9 3 ``` 第一步: ``` 3 7 4 10 13 15 ``` 第二步: ``` 3 20 19 ``` 得到解: ``` 23 ``` 同样的方法适应于任何行数的三角。

Code


import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public final class p067 {

    public static void main(String[] args) {
        long start = System.nanoTime();
        long result = run();
        long end = System.nanoTime();
        System.out.println(result);
        System.out.println((end - start) / 1000000 + "ms");
    }

    public static long run() {
        int[][] triangle = getTriangle();
        for (int i = triangle.length - 2; i >= 0; i--) {
            for (int j = 0; j < triangle[i].length; j++) {
                triangle[i][j] += Math.max(triangle[i + 1][j], triangle[i + 1][j + 1]);
            }
        }
        return triangle[0][0];
    }

    private static int[][] getTriangle() {
        Path path = Paths.get("C:/temp/p067_triangle.txt");
        try {
            List<String> lines = Files.readAllLines(path);
            int[][] triangle = new int[lines.size()][];
            for (int i = 0; i < lines.size(); i++) {
                String[] strs = lines.get(i).split(" ");
                int[] ints = new int[strs.length];
                for (int j = 0; j < ints.length; j++) {
                    ints[j] = Integer.valueOf(strs[j]);
                }
                triangle[i] = ints;
            }
            return triangle;
        } catch (IOException | NumberFormatException e) {
        }
        return null;
    }
}
7273
29ms