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.
首先我的思路是从上往下,时间比较长;
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int ret=0;
int n =triangle.size();
for(int i=1;i<n;i++ ){
List<Integer> dataList = triangle.get(i);
int len = dataList.size();
for(int j=0;j<len;j++){
if(j-1>=0 && j!=len -1){
if(triangle.get(i-1).get(j-1)< triangle.get(i-1).get(j)){
dataList.set(j, triangle.get(i-1).get(j-1)+dataList.get(j));
continue;
}
}
if(j==len -1){
dataList.set(j, triangle.get(i-1).get(j-1)+dataList.get(j));
break;
}
dataList.set(j, triangle.get(i-1).get(j)+dataList.get(j));
}
triangle.set(i, dataList);
}
ret = triangle.get(n-1).get(0);
for(int i=1;i<n;i++){
if(ret>triangle.get(n-1).get(i)){
ret=triangle.get(n-1).get(i);
}
}
return ret;
}
}
倒着写,反而不用考虑这个是不是越界,这个和最大最小整数的时候应该选择范围大的负数一样的。
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int n =triangle.size();
int[] tempList=new int[n];
for(int k=0;k<n;k++){
tempList[k]=triangle.get(n-1).get(k).intValue();
}
for(int i = n-2;i>=0;i--){
int len = triangle.get(i).size();
for(int j=0;j<len;j++){
tempList[j]=triangle.get(i).get(j)+ Math.min(tempList[j], tempList[j+1]);
}
}
return tempList[0];
}
}
哈哈哈。倒着,时间快,代码简单,这就告诉了我们,越界一定要想好如何避免。
更好的倒着:21-6-21
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int ret=Integer.MAX_VALUE;
int len=triangle.size();
int[] p=new int[len];
p[0]=triangle.get(0).get(0);
for(int i=1;i<len;i++){
p[i]=p[i-1];
for(int j=i;j>=0;j--){
if(j-1>=0) {
p[j]=Math.min(p[j],p[j-1]);
}
p[j]=p[j]+triangle.get(i).get(j);
}
}
for(int i=0;i<len;i++){
if(p[i]<ret){
ret=p[i];
}
}
return ret;
}
}