120. Triangle(dp)
2016-08-22 00:05
302 查看
题目:
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).
找最小代价路径,自底向上,采用dp,状态方程为:f(i, j) = min f(i + 1, j), f(i + 1, j + 1) + (i, j)
代码:public class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int n= triangle.size();
int[][] dp= new int
;
for(int i=0;i<n;i++)
{
for(int j=0;j<=i;j++){
dp[i][j]=triangle.get(i).get(j);
}
}
for(int i=n-2;i>=0;i--)
{
for(int j=0;j<=i;j++)
{
dp[i][j]+=Math.min(dp[i+1][j], dp[i+1][j+1]);
}
}
return dp[0][0];
}
}
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).
找最小代价路径,自底向上,采用dp,状态方程为:f(i, j) = min f(i + 1, j), f(i + 1, j + 1) + (i, j)
代码:public class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int n= triangle.size();
int[][] dp= new int
;
for(int i=0;i<n;i++)
{
for(int j=0;j<=i;j++){
dp[i][j]=triangle.get(i).get(j);
}
}
for(int i=n-2;i>=0;i--)
{
for(int j=0;j<=i;j++)
{
dp[i][j]+=Math.min(dp[i+1][j], dp[i+1][j+1]);
}
}
return dp[0][0];
}
}
相关文章推荐
- 120. Triangle(Array; DP, WPS)
- (DP)LeetCode#120. Triangle
- 【转】别人整理的DP大全
- FZU 1977 Pandora adventure (插头DP)
- ural1057(数位dp)
- 【HDU】4960 Another OCD Patient 【DP】
- Brackets - POJ 1955 dp
- spoj Balanced Numbers(数位dp)
- BZOJ 1212: [HNOI2004]L语言( dp + trie )
- POJ 2955-Brackets(括号匹配-区间DP)
- hdu FatMouse's Speed(DP)(打印路径)
- SSL2298 饥饿的牛(dp)
- 70. Climbing Stairs (dp)
- 简单dp&递推合集
- RQNOJ P579 商人的宣传(DP or DFS)
- 四边形不等式DP的总结
- hdu 1561 The more, The Better (树形dp)
- hdu 4960 Another OCD Patient dp(记忆化搜索)
- Food Delivery - ZOJ 3469 dp
- 10271 - Chopsticks (DP)