【leetcode】Array——Triangle(120)

来源:互联网 发布:js 自定义属性 data 编辑:程序博客网 时间:2024/06/06 01:48

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.


解题:自己的思路是从上往下,类似于动态规划DP,遍历的时候替换元素为到达当前位置最短路径

publicint minimumTotal(List<List<Integer>>triangle) {

introw = triangle.size();

for(inti=1;i<row;i++){

List<Integer>list = triangle.get(i);

for(intj=0;j<list.size();j++){

intup_min =0;

inttemp =0;

if(j==0){

up_min =triangle.get(i-1).get(0);

temp =list.get(0)+up_min;

}elseif(j==i){

up_min =triangle.get(i-1).get(j-1);

temp =list.get(j)+up_min;

}else{

intup_1 = triangle.get(i-1).get(j-1);

intup_2 = triangle.get(i-1).get(j);

temp =list.get(j)+((up_1<=up_2)?up_1:up_2);

}

list.set(j,temp);

}

}

//获取最后一行最小的数值

intresult = triangle.get(row-1).get(0);

for(inti=0;i<triangle.size();i++){

if(triangle.get(row-1).get(i)<=result){

result =triangle.get(row-1).get(i);

}

}

returnresult;


    }




改进:从下往上遍历

public int minimumTotal(List<List<Integer>> triangle) {

        for(int i = triangle.size() -2; i >= 0; i--)

            for(int j =0; j <= i; 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 0
原创粉丝点击