算法设计与分析: 3-7 数字三角形问题

3-7 数字三角形问题


问题描述

给定一个由n行数字组成的数字三角形,如下图所示:
数字三角形
试设计一个算法,计算出从三角形的顶至底的一条路径,使该路径经过的数字总和最大(每一步只能从一个数走到下一层上和它最近的左边的数或者右边的数)。

输入数据:
第一行是数字三角形的行数,接下来 n 行是数字三角形中的数字。


Java

import java.util.Scanner;

public class ShuZiSanJiaoXing {

    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        int n;
        int [][] triangle;

        /*
        input data:
        5
        7
        3 8
        8 1 0
        2 7 4 4
        4 5 2 6 5
        */
        while (true){
            n = input.nextInt();
            triangle = new int[n][n];

            for(int row=0; row<n; row++)
                for(int col=0; col<=row; col++)
                    triangle[row][col] = input.nextInt();

            //自底向上
            for(int row=n-2; row>=0; row--)
                for(int col=0; col<=row; col++)
                    if(triangle[row+1][col] > triangle[row+1][col+1])
                        triangle[row][col] += triangle[row+1][col];
                    else
                        triangle[row][col] += triangle[row+1][col+1];

            System.out.println(triangle[0][0]);
        }
    }
}

Input & Output

5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
30

王晓东《计算机算法设计与分析》(第3版)P90

猜你喜欢

转载自blog.csdn.net/ioio_/article/details/81014150