数字三角形-LintCode
来源:互联网 发布:开通知乎专栏 编辑:程序博客网 时间:2024/06/04 19:12
描述:
给定一个数字三角形,找到从顶部到底部的最小路径和。每一步可以移动到下面一行的相邻数字上。
注意事项:如果你只用额外空间复杂度O(n)的条件下完成可以获得加分,其中n是数字三角形的总行数。
样例:比如,给出下列数字三角形:
[
[2], [3,4], [6,5,7],[4,1,8,3]
]
从顶到底部的最小路径和为11 ( 2 + 3 + 5 + 1 = 11)。
思路:
通过思考,我们得到了如下规律;
我们建立一个一维数组f,f[n]表示当遍历到第m行时,三角形中第m行第n个数为终点的最小路径和,其更新计算方法为f[n]=min(f[n-1](上一行)+f[n](上一行)],遍历完三角形后得到的f[n]中的最小值即为最小路径和。
AC代码:
class Solution {public: /* * @param triangle: a list of lists of integers * @return: An integer, minimum path sum */ int minimumTotal(vector<vector<int>> &triangle) { // write your code here int f[9999999]; int m=triangle.size(); if(m==0)return 0; int n=triangle[m-1].size(); if(n==0)return 0; int minx; int i,j; f[0]=triangle[0][0]; for(i=1;i<m;i++) for(j=i;j>=0;j--) { if(j-1<0) f[j]=f[j]+triangle[i][j]; else if(j==i) f[j]=f[j-1]+triangle[i][j]; else f[j]=min(f[j],f[j-1])+triangle[i][j]; } minx=f[0]; for(j=0;j<n;j++) minx=min(minx,f[j]); return minx; }};
阅读全文
0 0
- LintCode Triangle 数字三角形
- lintcode-数字三角形-109
- lintcode ----数字三角形
- lintcode triangle 数字三角形
- 数字三角形-LintCode
- lintcode--数字三角形
- 数字三角形-LintCode
- LintCode 数字三角形
- [LintCode 109] 数字三角形(Python)
- Lintcode-动态规划-数字三角形
- LintCode: 109. 数字三角形 Java
- LintCode做题记录- 数字三角形
- LintCode刷题——数字三角形
- LintCode-三角形计数
- lintcode(382)三角形计数
- lintcode 三角形计数
- LintCode之三角形计数
- Lintcode三角形计数
- 利用SwitchySharp 和外网服务器实现vpn功能
- LeetCode 179 Largest Number
- 【《计算机网络(第七版)》学习笔记】一、 概述
- javaweb访问流程图
- JSP 实现登录注册功能
- 数字三角形-LintCode
- java求解一个线性规划约束问题
- ACM10月29日周日周末训练心得
- mysql中SQL执行过程详解
- Java NIO 详解---NIO中的异步网络IO
- HashMap 和 HashTable 到底哪不同 ?
- 图的深度和广度遍历
- 弹性碰撞(poj 3684)
- hexo博客系统搭建的完整过程