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];
}
}
注意点
题意理解清楚!!!