Lintcode168 Burst Balloons solution 题解

来源:互联网 发布:慕课网php百度网盘 编辑:程序博客网 时间:2024/06/06 01:17

【题目描述】

Given n balloons, indexed from 0 ton-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left and right are adjacent indices of i. After the burst, the left and right then becomes adjacent.

有n个气球,编号为0到n-1,每个气球都有一个分数,存在nums数组中。每次吹气球i可以得到的分数为nums[left] * nums[i] * nums[right],left和right分别表示i气球相邻的两个气球。当i气球被吹爆后,其左右两气球即为相邻。要求吹爆所有气球,得到最多的分数。

【题目链接】

www.lintcode.com/en/problem/burst-balloons/

【题目解析】

考虑分治法来处理的时候,如果选择以某个气球为分割点,那么其左边部分和右边部分都要依赖与那个气球,因此我们不能让这个气球先爆.也就是说我们选择分割点的时候不是选择先爆的气球,而是最后爆的气球,这样分成的左右两个部分将相互独立.即如果最后只剩下气球i,那么其最后只依赖与第0和n-1个气球,而在[0, i] 和 [i, n-1]两个区间是相互独立的。

这样我们就可以将问题分割为相互独立的子集.这样时间复杂为O(n^n). 但是在枚举各个分割点的时候会有很多重复的计算,因此我们可以保存已经计算过的区间.这样时间复杂度可以优化到O(n^3).

【参考答案】

www.jiuzhang.com/solutions/burst-balloons/