经典动态规划问题--数字三角形 POJ--1163

34 篇文章 0 订阅
28 篇文章 0 订阅

The Triangle

Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 35683 Accepted: 21357

Description

7
3   8
8   1   0
2   7   4   4
4   5   2   6   5

(Figure 1)
Figure 1 shows a number triangle. Write a program that calculates the highest sum of numbers passed on a route that starts at the top and ends somewhere on the base. Each step can go either diagonally down to the left or diagonally down to the right.

Input

Your program is to read from standard input. The first line contains one integer N: the number of rows in the triangle. The following N lines describe the data of the triangle. The number of rows in the triangle is > 1 but <= 100. The numbers in the triangle, all integers, are between 0 and 99.

Output

Your program is to write to standard output. The highest sum is written as an integer.

Sample Input

5
7
3 8
8 1 0 
2 7 4 4
4 5 2 6 5

Sample Output

30

解题思路:这道题目是动态规划的典型。其实递归,动态规划,分治从某种角度讲是十分的相近的。这个问题的子问题很明显是每次选择数字后对下一层的选择,每次都有两种。很容易想到用递归遍历每种解法,找到最大值。这种思路的好处是从上往下推,考虑比较正面。往往我们为了不超时间会开辟一个数组来存储我们已经计算得到的结果。也就是平常说的以空间换时间。

下面是递归的写法:

// 数字三角形问题.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include<memory.h>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
int a[110][110]={0};
int record[110][110]={0};
int n=0;
int max_sum(int i,int j);
int main()
{
	
	while(scanf("%d",&n)!=EOF)
	{
		memset(record,-1,sizeof(record));
		for(int i=0;i<n;i++)
			for(int j=0;j<=i;j++)
			    scanf("%d",&a[i][j]);
		int sum=max_sum(0,0);
		printf("%d",sum);
	}
	
	return 0;
}

int max_sum(int i,int j)
{
	if(i==n-1)
		return a[i][j];
	int left=0,right=0;
	if(record[i][j]==-1)
	{
		left=a[i][j]+max_sum(i+1,j);
		right=a[i][j]+max_sum(i+1,j+1);
		record[i][j]=left>right?left:right;
	}
	return record[i][j];
}


还有一种思考方式是从下往上推,具体来说就是假设轮到第i层的数字挑选他会从两个数字中和目前累计和最大的。

看下面这个例子,总共5层,

从第4层看。2会挑选5得到累加和7;7会挑选5得到累加和12;4会挑选6得到累加和10;下一个4会挑选6也得到10;

再看第3层。8会挑选累加和较大的7,他的累加和是12,以此类推·······直到最后比较3和8的累加和谁大,7和其相加。

7
3   8
8   1   0
2   7   4   4
4   5   2   6   5


 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值