#leetcode#Triangle
2015-06-18 12:01
197 查看
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
The minimum path sum from top to bottom is
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.
考虑题中所给例子, 转换成index来看是这样的
0 0
|
1 0
1
| \ | \
2 0
1 2
|
\ | \
| \
3 0
1 2 3
用一维dp的话,初始化为最下面一层, 从左往右遍历, dp[i][j] = min(dp[i +1][j], dp[i + 1][j + 1]) + triangle[i][j],
外层循环从最底下那层到第一层,(i = triangle.size() - 1 ~ 0)
观察上图可以得知 内层循环 (j = 0 ~ i)
每次写入dp[j]的时候会用到上一层的dp[j], dp[j + 1], 写入当前层的dp[j]并不会覆盖dp[j + 1], 所以一位数组就足够了
public class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
if(triangle == null || triangle.size() == 0){
return 0;
}
int size = triangle.size();
int[] dp = new int[triangle.get(size - 1).size()];
for(int i = 0; i < dp.length; i++){
dp[i] = triangle.get(size - 1).get(i);
}
for(int i = size - 2; i >= 0; i--){
for(int j = 0; j <= i; j++){
dp[j] = triangle.get(i).get(j) + Math.min(dp[j], dp[j + 1]);
}
}
return dp[0];
}
}
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.
考虑题中所给例子, 转换成index来看是这样的
0 0
|
1 0
1
| \ | \
2 0
1 2
|
\ | \
| \
3 0
1 2 3
用一维dp的话,初始化为最下面一层, 从左往右遍历, dp[i][j] = min(dp[i +1][j], dp[i + 1][j + 1]) + triangle[i][j],
外层循环从最底下那层到第一层,(i = triangle.size() - 1 ~ 0)
观察上图可以得知 内层循环 (j = 0 ~ i)
每次写入dp[j]的时候会用到上一层的dp[j], dp[j + 1], 写入当前层的dp[j]并不会覆盖dp[j + 1], 所以一位数组就足够了
public class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
if(triangle == null || triangle.size() == 0){
return 0;
}
int size = triangle.size();
int[] dp = new int[triangle.get(size - 1).size()];
for(int i = 0; i < dp.length; i++){
dp[i] = triangle.get(size - 1).get(i);
}
for(int i = size - 2; i >= 0; i--){
for(int j = 0; j <= i; j++){
dp[j] = triangle.get(i).get(j) + Math.min(dp[j], dp[j + 1]);
}
}
return dp[0];
}
}
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解
- LeetCode 2: Add Two Numbers (JAVA)
- LeetCode 1: Two Sum (JAVA)