Skip to content

Commit

Permalink
Triangle
Browse files Browse the repository at this point in the history
Change-Id: I048d685c459bb97fe0ccefcd20d0c3788264804f
  • Loading branch information
applewjg committed Jan 18, 2015
1 parent c5edc96 commit a6a1c9a
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions Triangle.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
Author: Andy, [email protected]
Date: May 14, 2013
Problem: Triangle
Difficulty: Easy
Source: https://oj.leetcode.com/problems/triangle/
Notes:
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.
Solution: Note that there are n elements in the n-th row (n starts from 1).
1. DP. Do not need additional spaces (happen in-place).
*/
public class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
for (int i = triangle.size() - 2; i >= 0; --i) {
List<Integer> cur = triangle.get(i);
List<Integer> next = triangle.get(i+1);
for (int j = 0; j < i + 1; ++j) {
cur.set(j, Math.min(next.get(j), next.get(j+1)) + cur.get(j));
}
}
return triangle == null ? 0 : triangle.get(0).get(0);
}
}

0 comments on commit a6a1c9a

Please sign in to comment.