【LeetCode-面試演算法經典-Java實現】【120-Triangle(三角形)】

來源:互聯網
上載者:User

標籤:三解形   矩陣   演算法   面試   java   

【120-Triangle(三角形)】【LeetCode-面試演算法經典-Java實現】【所有題目目錄索引】原題

  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.

題目大意

  給定一個三角形,找出從頂到底的最小路徑和,每一步可以從上一行移動到下一行相鄰的數字

解題思路

  遞推方程:
  f(0,0)=a[0][0]
  f(i,0)=a[i][0]+f(i-1,0) (i>0)
  f(i,i)=a[i][i]+f(i-1,i-1)(i>0)
  f(i,j)=a[i][j]+MIN(f(i-1,j),f(i-1,j-1))(0

代碼實現

演算法實作類別

import java.util.List;public class Solution {    public int minimumTotal(List<List<Integer>> triangle) {        if (triangle == null || triangle.size() < 1) {            return 0;        }        // 建立數組的第二維度        int[][] minSum = new int[triangle.size()][];        // 建立數組的第一維度        for (int i = 0; i < minSum.length; i++) {            minSum[i] = new int[i + 1];        }        // 設定第一行        minSum[0][0] = triangle.get(0).get(0);        // 設定其它行        for (int i = 1; i < minSum.length; i++) {            List<Integer> line = triangle.get(i);            for (int j = 0; j < minSum[i].length; j++) {                if (j == 0) {                    minSum[i][0] = line.get(0) + minSum[i - 1][0];                } else if (i == j) {                    minSum[i][j] = line.get(j) + minSum[i - 1][j - 1];                } else if (j < i) {                    minSum[i][j] = line.get(j) + Math.min(minSum[i - 1][j], minSum[i - 1][j - 1]);                }            }        }        //找最後一行的最小值就是所求的解        int min = minSum[minSum.length - 1][0];        int length = minSum[minSum.length - 1].length;        for (int i = 1; i < length; i++) {            if (min > minSum[length - 1][i]) {                min = minSum[length - 1][i];            }        }        return min;    }}
評測結果

  點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。

特別說明歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/47651229】

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

【LeetCode-面試演算法經典-Java實現】【120-Triangle(三角形)】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.