POJ 1163 The Triangle

本文介绍了一种经典的算法问题——寻找数字三角形中从顶点到底部的最大路径和。通过四种不同的解决思路,逐步优化算法效率,从最初的简单递归到最终采用动态规划并运用滚动数组减少空间占用。

题目

总时间限制: 1000ms 内存限制: 65536kB
描述
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.
输入
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.
输出
Your program is to write to standard output. The highest sum is written as an integer.
样例输入
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
样例输出
30

思路1

简单的递归,MaxSum(r, j)表示从第r行第j列开始算,最大的元素和。时间复杂度O(2N),这样肯定超时。

代码1

def MaxSum(r, j, nums, N):
    if r == N - 1:
        return nums[r][j]
    sum1 = MaxSum(r + 1, j, nums, N)
    sum2 = MaxSum(r + 1, j + 1, nums, N)
    return (nums[r][j] + sum1) if sum1 > sum2 else (nums[r][j] + sum2)
while True:
    try:
        N = int(input().strip())
        nums = []
        for _ in range(N):
            nums.append([int(i) for i in input().strip().split()])
        print(MaxSum(0, 0, nums, N))
    except:
        break

思路2

用一个数组maxSum记录计算过的点,节省时间。
时间复杂度O(N2)

代码2

def MaxSum(r, j, nums, maxSum, N):
    if r == N - 1:
        maxSum[r][j] = nums[r][j]
        return nums[r][j]
    if maxSum[r + 1][j] == -1:
        sum1 = MaxSum(r + 1, j, nums, maxSum, N)
        maxSum[r + 1][j] = sum1
    else:
        sum1 = maxSum[r + 1][j]
    if maxSum[r + 1][j + 1] == -1:
        sum2 = MaxSum(r + 1, j + 1, nums, maxSum, N)
        maxSum[r + 1][j + 1] = sum2
    else:
        sum2 = maxSum[r + 1][j + 1]
    return (nums[r][j] + sum1) if sum1 > sum2 else (nums[r][j] + sum2)
while True:
    try:
        N = int(input().strip())
        nums = []
        maxSum = []
        for _ in range(N):
            nums.append([int(i) for i in input().strip().split()])
        for i in range(len(nums)):
            maxSum.append([-1 for j in nums[i]])
        print(MaxSum(0, 0, nums, maxSum, N))
    except:
        break

思路3

把思路2代码改成动态规划,时间复杂度O(N2)

MaxSum(r,j)={d(r,j),r=NMax{MaxSum(r+1,j),MaxSum(r+1,j+1)}+d(r,j),others

代码3

while True:
    try:
        N = int(input().strip())
        nums = []
        maxSum = []
        for _ in range(N):
            nums.append([int(i) for i in input().strip().split()])
        for i in range(len(nums)):
            maxSum.append([-1 for j in nums[i]])
        for i in range(N):
            maxSum[N - 1][i] = nums[N - 1][i]

        for i in range(N - 1)[::-1]:
            for j in range(len(nums[i])):
                maxSum[i][j] = (nums[i][j] + maxSum[i + 1][j]) if maxSum[i + 1][j] > maxSum[i + 1][j + 1] else (nums[i][j] + maxSum[i + 1][j + 1])
        print(maxSum[0][0])
    except:
        break

思路4

把动态规划使用滚动数组,动态更新数组的值,可以节省空间。

代码4

while True:
    try:
        N = int(input().strip())
        nums = []
        maxSum = []
        for _ in range(N):
            nums.append([int(i) for i in input().strip().split()])
        for i in range(N):
            maxSum.append(nums[N - 1][i])
        for i in range(N - 1)[::-1]:
            for j in range(len(nums[i])):
                maxSum[j] = (nums[i][j] + maxSum[j]) if maxSum[j] > maxSum[j + 1] else (nums[i][j] + maxSum[j + 1])
        print(maxSum[0])
    except:
        break
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值