Leetcode——动态规划triangle

palindrome-partitioning-ii

题目描述:
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers(相邻的) on the row below.

For example, given the following triangle

[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).

Note:

Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.

知识点:
ArrayList,leetcode,动态规划
解题思路:
【个人思路】
这个题是典型的动态规划的题。就想到用时间换空间,把之前计算过的信息保存起来。首先需要分析题目,这是一个三角形的结构,所以结构依次为1,2,3,4…。而且需要注意题目要求的是相邻的下一层的数字,所以会有两种结果。和leetcode198真的是异曲同工之妙!!!
具体代码:

import java.util.ArrayList;
import java.util.Arrays;

public class triangle_2 {

  public static void main(String[] args){
  	ArrayList<ArrayList<Integer>> triangle=new ArrayList<ArrayList<Integer>>();
  	triangle.add(new ArrayList<Integer>((Arrays.asList(-1))));
  	triangle.add(new ArrayList<Integer>((Arrays.asList(2,3))));
  	triangle.add(new ArrayList<Integer>((Arrays.asList(1,-1,-3))));
//		triangle.add(new ArrayList<Integer>((Arrays.asList(4,1,8,3))));
//		for(ArrayList<Integer> arrayList:triangle){
//				System.out.println(arrayList);
//		}
  	int result;
  	result=minimumTotal(triangle);
  	System.out.println(result);
  	
  }

  private static int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
  	// TODO Auto-generated method stub
  	int len=triangle.size();
  	if(len==0) return 0;
  	int[] dp=new int[triangle.size()];
  	for(int i=0;i<triangle.size();i++){
  		dp[i]=triangle.get(triangle.size()-1).get(i);
  	}
  	//从倒数第二层开始
  	for(int i=triangle.size()-2;i>=0;i--){
  		ArrayList<Integer> curlist=triangle.get(i);
  		for(int j=0;j<curlist.size();j++)
  			dp[j]=Math.min(curlist.get(j)+dp[j],curlist.get(j)+dp[j+1]);
  	}
  	return dp[0];
  	
  }
  
  
}



注意点
题意理解清楚!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值