IT技術小屋

          秋風秋雨,皆入我心

            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            38 隨筆 :: 1 文章 :: 19 評論 :: 0 Trackbacks
          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.

          本題本來的想法是用遞歸做,實現代碼如下:
           1 public class Solution {
           2     public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
           3         int row = triangle.size();
           4         return findMinPath(triangle, 0, 0, row);
           5     }
           6 
           7     private int findMinPath(ArrayList<ArrayList<Integer>> triangle, int row,
           8             int col, int totalRow) {
           9         if (row == totalRow - 1) {
          10             return triangle.get(row).get(col);
          11         } else {
          12             return triangle.get(row).get(col) + Math.min(findMinPath(triangle, row + 1, col, totalRow), findMinPath(triangle, row + 1, col + 1, totalRow));
          13         }
          14     }
          15 }
          提交之后發現超時,于是考慮到可能是遞歸的開銷問題,考慮用迭代解題。實現如下:
           1 public class Triangle {
           2     public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
           3         int n = triangle.size() - 1;
           4         int[] path = new int[triangle.size()];
           5         for (int o = 0; o < triangle.get(n).size(); o++) {
           6             path[o] = triangle.get(n).get(o);
           7         }
           8         for (int i = triangle.size() - 2; i >= 0; i--) {
           9             for (int j = 0, t = 0; j < triangle.get(i + 1).size() - 1; j++, t++) {
          10                 path[t] = triangle.get(i).get(t)
          11                         + Math.min(path[j], path[j + 1]);
          12             }
          13         }
          14         return path[0];
          15     }
          16 }
          這個解法的核心是從葉節點自底向上構造解空間。
          posted on 2013-12-25 11:31 Meng Lee 閱讀(159) 評論(0)  編輯  收藏 所屬分類: Leetcode
          主站蜘蛛池模板: 韶关市| 安岳县| 伊川县| 新田县| 濮阳市| 浮梁县| 盈江县| 海盐县| 巫溪县| 新平| 奉化市| 万盛区| 南充市| 同心县| 吴堡县| 年辖:市辖区| 镇巴县| 楚雄市| 安多县| 岑溪市| 宜都市| 淮南市| 天祝| 香港| 岑巩县| 遂溪县| 延津县| 时尚| 宁远县| 香港 | 长沙市| 大邑县| 衢州市| 普兰县| 方山县| 崇义县| 翁源县| 大港区| 东乌珠穆沁旗| 黄梅县| 通海县|