LintCode: Triangle

简介:

C++

逆推

复制代码
 1 class Solution {
 2 public:
 3     /**
 4      * @param triangle: a list of lists of integers.
 5      * @return: An integer, minimum path sum.
 6      */
 7     int minimumTotal(vector<vector<int> > &triangle) {
 8         // write your code here
 9         if (triangle.size() == 0)
10             return 0;
11             
12         vector<int> dp(triangle.size());
13         
14         dp[0] = triangle[0][0];
15         for(int i = 1; i < triangle.size(); i++)
16             for(int j = triangle[i].size() - 1; j >= 0; j--)
17                 if (j == 0)
18                     dp[j] = dp[j] + triangle[i][j];
19                 else if (j == triangle[i].size() - 1)
20                     dp[j] = dp[j-1] + triangle[i][j];
21                 else
22                     dp[j] = min(dp[j-1], dp[j]) + triangle[i][j];
23                     
24         int ret = INT_MAX;
25         for(int i = 0; i < dp.size(); i++)
26             ret = min(ret, dp[i]);
27             
28         return ret;  
29     }
30 };
复制代码

 C++,修改原数组

复制代码
 1 class Solution {
 2 public:
 3     /**
 4      * @param triangle: a list of lists of integers.
 5      * @return: An integer, minimum path sum.
 6      */
 7     int minimumTotal(vector<vector<int> > &triangle) {
 8         // write your code here
 9         for (int i = triangle.size() - 2; i >= 0; --i){
10           for (int j = 0; j < i + 1; ++j){
11             if(triangle[i+1][j] > triangle[i+1][j+1]){
12               triangle[i][j] += triangle[i+1][j+1];
13             }else{
14               triangle[i][j] += triangle[i+1][j];
15             }
16           }
17         }
18         return triangle[0][0];
19     }
20 };
复制代码

 

本文转自ZH奶酪博客园博客,原文链接:http://www.cnblogs.com/CheeseZH/p/5006838.html,如需转载请自行联系原作者

相关文章
|
Java Go
POJ 1163 The Triangle
POJ 1163 The Triangle
101 0
LeetCode 118:杨辉三角 II Pascal's Triangle II
公众号:爱写bug(ID:icodebugs)作者:爱写bug 给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。 Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle. Note that the row index starts from 0. 在杨辉三角中,每个数是它左上方和右上方的数的和。
916 0
|
Java 索引 Python
Leetcode 54:Spiral Matrix 螺旋矩阵
54:Spiral Matrix 螺旋矩阵 Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. 给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
827 0
Leetcode 118:Pascal's Triangle 杨辉三角
118:Pascal's Triangle 杨辉三角 Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. 给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
981 0