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];
  	
  }
  
  
}



注意點
題意理解清楚!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章