zoukankan      html  css  js  c++  java
  • 16-算法训练 数字三角形

            算法训练 数字三角形  
    时间限制:1.0s   内存限制:256.0MB
        
    问题描述
      (图3.1-1)示出了一个数字三角形。 请编一个程序计算从顶至底的某处的一条路
      径,使该路径所经过的数字的总和最大。
      ●每一步可沿左斜线向下或右斜线向下走;
      ●1<三角形行数≤100;
      ●三角形中的数字为整数0,1,…99;


      .
      (图3.1-1)
    输入格式
      文件中首先读到的是三角形的行数。

      接下来描述整个三角形
    输出格式
      最大总和(整数)
    样例输入
    5
    7
    3 8
    8 1 0
    2 7 4 4
    4 5 2 6 5
    样例输出
    30
     
    思路:dp, 注意用记忆数组,否则超时!!!
    import java.util.Scanner;
    
    public class Main {
    	public static int n;
    	public static int[][] map = new int[110][120];
    	public static int[][] sum = new int[110][120];
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Scanner cin = new Scanner(System.in);
    		n = cin.nextInt();
    		for(int i = 0; i < n; i++) {
    			for(int j = 0; j <= i; j++) {
    				map[i][j] = cin.nextInt();
    //				System.out.println(sum[i][j]);
    			}
    		}
    		System.out.println(get(0,0));
    	}
    
    	public static int get(int i, int j) {
    		if(sum[i][j] != 0) {   //判断之前是否访问过,避免重复搜索而超时
    			return sum[i][j];
    		}
    		if(i == n - 1) {
    			return sum[i][j] = map[i][j];
    		}
    		return sum[i][j] = Math.max( get(i+1,j), get(i+1,j+1)) + map[i][j];
    	}
    }
    

      

  • 相关阅读:
    ABAP TCode
    SAP 常用的事务代码
    SAP FI TCode
    Little Tutorials的一篇文章断言:UML(统一建模语言)正在死亡:
    SAP PP TCode
    [ZT]解密中国IT人十大职业现状
    User Exit Query
    SAP客户端多语言设置
    一个女CIO的诞生
    DIY防奸手册之 主流硬盘型号解惑篇
  • 原文地址:https://www.cnblogs.com/zhumengdexiaobai/p/10367523.html
Copyright © 2011-2022 走看看