Leetcode Triangle

12 篇文章 0 订阅

Leetcode Triangle 相关代码,使用dp方法完成,c++代码如下,并提供简单的测试代码。

#include <iostream>
#include <unordered_set>
#include <vector>
#include <string>
using namespace std;

class Solution {
public:
    int minimumTotal(vector<vector<int> >& triangle) {
        if (triangle.size() == 0) {
            return 0;
        }
        int len = triangle.size();
        int min;
        int pre = 0; // remember the previous re
        vector<int> re(len, 0);
        re[0] = triangle[0][0];
        for (int i = 1; i < len; i ++) {
            for (int j = 0; j <= i; j ++) {
                // the re[i] has no valid value in the previous line
                if (j != i) {
                    min = re[j] + triangle[i][j];
                }
                // the re[-1] is invalid, the pre remember the re[j - 1]
                if ((j >= 1 && pre + triangle[i][j] < min) || j == i) {
                    min = pre + triangle[i][j];
                }
                pre = re[j];
                re[j] = min;
            }
        }
        min = re[0];
        // find the minimal result in re
        for (vector<int>::iterator it = re.begin(); it != re.end(); it ++) {
            if (*it < min) {
                min = *it;
            }
        }
        return min;
    }
};


int main() {
    Solution * so = new Solution();
    vector<vector<int> > test;
    vector<int> a;
    a.push_back(-1);
    test.push_back(a);
    a.clear();
    a.push_back(2);
    a.push_back(3);
    test.push_back(a);
    a.clear();
    a.push_back(1);
    a.push_back(-1);
    a.push_back(-3);
    test.push_back(a);
    cout<<"the minimal result is: "<<so->minimumTotal(test)<<endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值