-
Notifications
You must be signed in to change notification settings - Fork 171
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |