leetcode 120 Triangle ----- java

來源:互聯網
上載者:User

標籤:log   mat   top   path sum   for   ble   etc   row   return   

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.

 

 求出最小的路徑。

第一次做使用遞迴,逾時了。

public class Solution {    public int minimumTotal(List<List<Integer>> triangle) {int len = triangle.size();        int result = triangle.get(0).get(0);        result = getResult(result,0,0,triangle);                return result;                    }    public static int getResult(int result,int pos,int num,List<List<Integer>> triangle){        if( num == triangle.size()-1 )            return result;        int num1 = triangle.get(num+1).get(pos);        int ans = result;        ans += num1;        ans = getResult(ans,pos,num+1,triangle);        num1 = triangle.get(num+1).get(pos+1);        result += num1;        result = getResult(result,pos+1,num+1,triangle);        return ans>result?result:ans;    }}

 

 所以還是需要用DP。  比較簡單的DP應用。
public class Solution {    public int minimumTotal(List<List<Integer>> triangle) {                int height = triangle.size();        int[] dp = new int[height];        dp[0] = dp[0]+triangle.get(0).get(0);        for( int i = 1;i<height;i++){            int a = dp[0],b = dp[1];            dp[0] = dp[0]+triangle.get(i).get(0);            for( int j = 1;j<i;j++){                dp[j] = Math.min(a,b)+triangle.get(i).get(j);                a = b;                b = dp[j+1];            }            dp[i] = a+triangle.get(i).get(i);        }        int result = dp[0];        for( int i = 1;i<height;i++)            result = Math.min(result,dp[i]);                return result;        }}

 

  

leetcode 120 Triangle ----- java

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.