[LeetCode] Triangle
2014-03-10 21:01
288 查看
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
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:
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:
class Solution { public: int minimumTotal(vector<vector<int> > &triangle) { int n = triangle.size(); if(n == 0) return 0; int *sum = new int[n + 1]; sum[0] = triangle[0][0]; for(int i = 1;i < n;i++) { sum[i] = sum[i - 1] + triangle[i][i]; for(int j = i - 1;j > 0;j--) sum[j] = min(sum[j], sum[j - 1]) + triangle[i][j]; sum[0] = sum[0] + triangle[i][0]; } int minS = 2147483647; for(int i = 0;i < n;i++) if(sum[i] < minS) minS = sum[i]; return minS; } };
相关文章推荐
- Cmarkup 使用总结 xml解析
- 黑马程序员___构造函数
- 微信平台3G模板制作指南
- (上节)Spring+JDBC+Struts;实现图片上传;配置的属性默认dbc用单例模式,action一定要scope=“prototype”
- Android图片对比源码
- hive 桶相关特性分析
- Mem系列函数与Str系列函数总结(二) memcmp与strcmp/strncmp
- linux学习笔记3:系统命令
- Puppet系列之五:Puppet报告系统Dashboard安装与配置
- java实现堆排序,本人略菜,求指教
- 6182 Ginkgo Numbers
- Playing with ptrace, Part I
- 1048. Inverso
- Django的安装
- Java进击(三)容器类
- Nginx gzip static静态压缩
- linux上未分区硬盘的格式化实践
- HDU 2222 AC自动机
- C++ deque(double-ended-queue)双端队列
- 中介者设计模式--练习