标签:leetcode
https://oj.leetcode.com/problems/triangle/
http://blog.csdn.net/linhuanmars/article/details/23230657
public class Solution { public int minimumTotal(List<List<Integer>> triangle) { // Solution A: // return minimumTotal_MaintainSums(triangle); // Solution B: return minimumTotal_NoExtraSpace(triangle); } ///////////////////////// // Solution B: NoExtraSpace // // Use Extra O(n) to maintain current row. // Use triangle to maintain sums. private int minimumTotal_NoExtraSpace(List<List<Integer>> triangle) { List<Integer> extra = new ArrayList<>(triangle.get(triangle.size() - 1).size()); for (int i = 1 ; i < triangle.size() ; i ++) { // Copy this row to extra memory for next iteration using. extra.clear(); for (int j : triangle.get(i)) extra.add(j); // Calculating this row, change it to sums. for (int j = 0 ; j < triangle.get(i).size() ; j ++) { int v = Math.min(val(triangle, i - 1, j - 1), val(triangle, i - 1, j)); v = v += extra.get(j); triangle.get(i).set(j, v); } } List<Integer> lastlevel = triangle.get(triangle.size() - 1); int min = Integer.MAX_VALUE; for (int i : lastlevel) { if (i < min) min = i; } return min; } ///////////////////////// // Solution A: MaintainSums // // Maintain sums in another List<List<Integer>> // private int minimumTotal_MaintainSums(List<List<Integer>> triangle) { // Assumes // Not null. // triangle.size >= 1 List<List<Integer>> sums = new ArrayList<>(); sums.add(Collections.<Integer> singletonList(triangle.get(0).get(0))); for (int i = 1 ; i < triangle.size() ; i ++) { // Level size int levelsize = i + 1; List<Integer> newSum = new ArrayList<>(levelsize); for (int j = 0 ; j < levelsize ; j ++) { int v = Math.min(val(sums, i - 1, j - 1), val(sums, i - 1, j)); v = v += triangle.get(i).get(j); newSum.add(v); } sums.add(newSum); } List<Integer> lastlevel = sums.get(sums.size() - 1); int min = Integer.MAX_VALUE; for (int i : lastlevel) { if (i < min) min = i; } return min; } private int val(List<List<Integer>> t, int row, int index) { List<Integer> level = t.get(row); if (index < 0 || index >= level.size()) return Integer.MAX_VALUE; return level.get(index); } }
标签:leetcode
原文地址:http://7371901.blog.51cto.com/7361901/1599810