LeetCode Triangle

本文介绍了一个通过动态规划求解三角形路径最小和的问题。该算法从底部开始逐层计算,选择每一步到达当前位置的最小路径和。通过具体代码实现展示了如何避免路径交叉,并给出了一个示例程序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目得说明路径不能跨越,否则的话,每层找最小的就可以了。为什么多提交两次呢?dp[j] = (dp[j]>dp[j+1]?dp[j+1]:dp[j]) + triangle[i][j];要是条件表达式不加括号的话不可以,那样的话后面的加法就没加上。还有一点就是j从小到大遍历,否则的话会覆盖结果,正常人都会从小到大。

// LeetCode_Triangle.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;

int minimumTotal(vector<vector<int> > &triangle) {
	int row = triangle.size();
	int column;
	int ret = 0;
	if(row!=0)
		column = triangle[row-1].size();
	else
		return ret;
	int *dp = new int[column];
	for(int i=0;i<column;i++)
		dp[i] = triangle[row-1][i];
	for (int i=row-2;i>=0;i--)
	{
		for (int j=0;j<=i;j++)
		{
			dp[j] = (dp[j]>dp[j+1]?dp[j+1]:dp[j]) + triangle[i][j];
		}
	}
	ret = dp[0];
	delete[] dp;
	return ret;
}
int _tmain(int argc, _TCHAR* argv[])
{
	vector<int> temp;
	vector<vector<int> > tri;
	temp.push_back(-1);
	tri.push_back(temp);
	temp.clear();
	temp.push_back(2);
	temp.push_back(3);
	tri.push_back(temp);
	temp.clear();
	temp.push_back(1);
	temp.push_back(-1);
	temp.push_back(-1);
	tri.push_back(temp);
	cout<<minimumTotal(tri);
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值