Leetcode Triangle 解题报告

44 篇文章 0 订阅
43 篇文章 0 订阅

Leetcode Triangle 

http://oj.leetcode.com/problems/triangle/

一道动态规划的经典题,POJ 1163 也是同一类型题,唯一区别在于Leetcode求最小值,POJ 1163求最大值。

递推公式是关键,假设原数组可以被修改,递推公式为:array[i][j] = array[i][j] + Math.max(array[i-1][j-1],array[i-1][j]);

从上向下每个路径的最小值都由上层的两个相邻节点决定。

发现从下向上计算的话,可以少考虑很多边界问题。

POJ 1163 AC的代码如下所示:

import java.util.Scanner;


public class Main{
    public static void main(String[] args) {
    	Scanner scan = new Scanner(System.in);  
    	int count = scan.nextInt();
    	int [][] array = new int [count][count];
    	for(int i=0;i<count;i++) {
        	for(int j=0;j<=i;j++) {
        		array[i][j] = scan.nextInt();
        	}
    	}

    	if (count>1) {
        	for(int i=count-2;i>=0;i--) {
            	for(int j=0;j<count-1;j++) {
                	array[i][j] = array[i][j] + Math.max(array[i+1][j],array[i+1][j+1]);
            	}
        	}
    	}
    	if(count==0) {
       		System.out.println(0);
    	} else {
       		System.out.println(array[0][0]);
    	}
	}
}

Leetcode Triangle AC的代码如下所示:

public class Solution {
public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
    // Start typing your Java solution below
    // DO NOT write main() function
    for(int i = triangle.size() - 2; i >= 0; i--)
    {
        for(int j = 0; j < triangle.get(i).size(); j++)
        {
            triangle.get(i).set(j, triangle.get(i).get(j) + Math.min(triangle.get(i + 1).get(j), triangle.get(i + 1).get(j + 1)));
        }
    }
    return triangle.get(0).get(0);
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值