IT技術(shù)小屋

          秋風(fēng)秋雨,皆入我心

            BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理 ::
            38 隨筆 :: 1 文章 :: 19 評(píng)論 :: 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.

          本題本來的想法是用遞歸做,實(shí)現(xiàn)代碼如下:
           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 }
          提交之后發(fā)現(xiàn)超時(shí),于是考慮到可能是遞歸的開銷問題,考慮用迭代解題。實(shí)現(xiàn)如下:
           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 }
          這個(gè)解法的核心是從葉節(jié)點(diǎn)自底向上構(gòu)造解空間。
          posted on 2013-12-25 11:31 Meng Lee 閱讀(159) 評(píng)論(0)  編輯  收藏 所屬分類: Leetcode
          主站蜘蛛池模板: 象山县| 隆德县| 定安县| 阿巴嘎旗| 佳木斯市| 交城县| 建平县| 梁平县| 班戈县| 吕梁市| 封丘县| 双流县| 临泽县| 东乡族自治县| 潮州市| 鲁甸县| 安宁市| 德阳市| 贡觉县| 永修县| 开封市| 建始县| 绥芬河市| 江西省| 曲周县| 当雄县| 蒙山县| 资溪县| 香格里拉县| 无棣县| 棋牌| 望谟县| 金坛市| 米易县| 阜城县| 东乌珠穆沁旗| 桐梓县| 和顺县| 洪湖市| 温宿县| 海林市|