您的位置:首页 > 其它

#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

[
[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